接入设备故障告警和场站实时任务进度
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../../core/network/mqtt/domain/interfaces/mqtt_client.dart';
|
||||
import '../../../../core/network/mqtt/domain/models/mqtt_message.dart';
|
||||
import '../../domain/entities/device_alarm.dart';
|
||||
import '../models/device_alarm_model.dart';
|
||||
|
||||
class DeviceAlarmMqttDataSource {
|
||||
const DeviceAlarmMqttDataSource(this.client);
|
||||
final MqttClient client;
|
||||
|
||||
Stream<List<DeviceAlarm>> watch(String deviceCode) {
|
||||
final code = deviceCode.trim();
|
||||
if (code.isEmpty) {
|
||||
debugPrintSynchronously('[设备告警][订阅] SN为空,无法构建topic');
|
||||
return Stream.error(const FormatException('Missing device code'));
|
||||
}
|
||||
final messages = client.messageStream;
|
||||
if (messages == null) {
|
||||
debugPrintSynchronously('[设备告警][订阅] MQTT消息流为空 SN=$code');
|
||||
return Stream.error(StateError('MQTT message stream unavailable'));
|
||||
}
|
||||
|
||||
final topic = 'device/$code/error/post';
|
||||
StreamSubscription<MqttMessage>? listener;
|
||||
Future<void>? subscribing;
|
||||
late final StreamController<List<DeviceAlarm>> controller;
|
||||
controller = StreamController<List<DeviceAlarm>>(
|
||||
onListen: () {
|
||||
debugPrintSynchronously(
|
||||
'[设备告警][订阅] 挂载消息监听 topic=$topic connected=${client.isConnected}',
|
||||
);
|
||||
// 沿用现有客户端:先接消息,再订阅,避免漏掉 retained/首帧。
|
||||
listener = messages
|
||||
.where((message) => message.topic == topic)
|
||||
.listen(
|
||||
(message) {
|
||||
debugPrintSynchronously('[设备告警] 收到 topic=${message.topic}');
|
||||
debugPrintSynchronously(
|
||||
'[设备告警] payload=${message.payload}',
|
||||
wrapWidth: 800,
|
||||
);
|
||||
try {
|
||||
final decoded = jsonDecode(message.payload);
|
||||
if (decoded is! Map) {
|
||||
throw const FormatException('Invalid alarm message');
|
||||
}
|
||||
final data = decoded['data'];
|
||||
final body = data is Map ? data : decoded;
|
||||
final type = body['type'] ?? decoded['type'];
|
||||
if (type != null && type != 'device_error_push') {
|
||||
debugPrintSynchronously(
|
||||
'[设备告警] 忽略消息类型 topic=$topic type=$type',
|
||||
);
|
||||
return;
|
||||
}
|
||||
final payload = body['alarms'];
|
||||
final List rows;
|
||||
if (payload is List) {
|
||||
rows = payload;
|
||||
} else if (payload == null &&
|
||||
(body.containsKey('alarmNo') ||
|
||||
body.containsKey('alarmTitle'))) {
|
||||
rows = [body];
|
||||
} else {
|
||||
throw const FormatException(
|
||||
'Missing alarm list or alarm record',
|
||||
);
|
||||
}
|
||||
final alarms = <DeviceAlarm>[];
|
||||
for (final row in rows) {
|
||||
if (row is! Map) continue;
|
||||
try {
|
||||
alarms.add(
|
||||
DeviceAlarmModel.fromJson(row, allowMissingId: true),
|
||||
);
|
||||
} on FormatException catch (error) {
|
||||
debugPrintSynchronously('[设备告警] 忽略无效记录 $topic: $error');
|
||||
}
|
||||
}
|
||||
if (rows.isNotEmpty && alarms.isEmpty) {
|
||||
throw const FormatException('No valid alarm records');
|
||||
}
|
||||
debugPrintSynchronously(
|
||||
'[设备告警] 解析完成 topic=$topic 原始=${rows.length} 有效=${alarms.length}',
|
||||
);
|
||||
controller.add(List.unmodifiable(alarms));
|
||||
} on FormatException catch (error, stack) {
|
||||
debugPrintSynchronously('[设备告警] 消息解析失败 $topic: $error');
|
||||
controller.addError(error, stack);
|
||||
}
|
||||
},
|
||||
onError: controller.addError,
|
||||
onDone: controller.close,
|
||||
);
|
||||
// 客户端负责连接恢复、重订阅与订阅引用计数。
|
||||
subscribing = Future.sync(() => client.subscribe(topic)).catchError((
|
||||
Object error,
|
||||
StackTrace stack,
|
||||
) {
|
||||
debugPrintSynchronously('[设备告警] 订阅失败 topic=$topic error=$error');
|
||||
if (!controller.isClosed) controller.addError(error, stack);
|
||||
});
|
||||
},
|
||||
onCancel: () async {
|
||||
await listener?.cancel();
|
||||
await subscribing;
|
||||
try {
|
||||
await client.unsubscribe(topic);
|
||||
debugPrintSynchronously('[设备告警] 退订完成 topic=$topic');
|
||||
} catch (error) {
|
||||
debugPrintSynchronously('[设备告警] 释放订阅失败 $topic: $error');
|
||||
}
|
||||
},
|
||||
);
|
||||
return controller.stream;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
|
||||
class DeviceAlarmRemoteDataSource {
|
||||
const DeviceAlarmRemoteDataSource(this.dio);
|
||||
final Dio dio;
|
||||
|
||||
Future<void> handle(int alarmId) async {
|
||||
debugPrint(
|
||||
'[设备告警] POST ${HttpApiConsts.handleDeviceAlarm} alarmId=$alarmId handleStatus=2',
|
||||
);
|
||||
final response = await dio.post<dynamic>(
|
||||
HttpApiConsts.handleDeviceAlarm,
|
||||
data: {'alarmId': alarmId, 'handleStatus': 2},
|
||||
);
|
||||
final body = response.data;
|
||||
debugPrint(
|
||||
'[设备告警] 处理接口返回 alarmId=$alarmId HTTP=${response.statusCode} body=$body',
|
||||
wrapWidth: 800,
|
||||
);
|
||||
// 沿用项目统一业务响应约定,仅在后端明确成功后更新状态。
|
||||
if (response.statusCode != 200 || body is! Map) {
|
||||
throw const DeviceAlarmRemoteException('');
|
||||
}
|
||||
if ('${body['code']}' != '200' || body['data'] == false) {
|
||||
throw DeviceAlarmRemoteException(body['msg']?.toString() ?? '');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DeviceAlarmRemoteException implements Exception {
|
||||
const DeviceAlarmRemoteException(this.message);
|
||||
final String message;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import '../../domain/entities/device_alarm.dart';
|
||||
|
||||
class DeviceAlarmModel {
|
||||
static DeviceAlarm fromJson(
|
||||
Map<dynamic, dynamic> json, {
|
||||
bool allowMissingId = false,
|
||||
}) {
|
||||
final id = int.tryParse('${json['id']}');
|
||||
final missingPushId =
|
||||
allowMissingId &&
|
||||
json['id'] == null &&
|
||||
(json['alarmNo']?.toString().trim().isNotEmpty ?? false) &&
|
||||
((json['alarmTitle']?.toString().trim().isNotEmpty ?? false) ||
|
||||
(json['alarmContent']?.toString().trim().isNotEmpty ?? false));
|
||||
if ((id == null || id <= 0) && !missingPushId) {
|
||||
throw const FormatException('Invalid alarm ID');
|
||||
}
|
||||
String text(String key) => json[key]?.toString().trim() ?? '';
|
||||
DateTime? time(String key) {
|
||||
final value = json[key];
|
||||
if (value is! List) return DateTime.tryParse(text(key));
|
||||
// Java LocalDateTime 的数组格式:[年,月,日,时,分,秒,纳秒]。
|
||||
if (value.length != 6 && value.length != 7) return null;
|
||||
final parts = <int>[];
|
||||
for (final item in value) {
|
||||
final parsed = int.tryParse('$item');
|
||||
if (parsed == null) return null;
|
||||
parts.add(parsed);
|
||||
}
|
||||
final nanos = parts.length == 7 ? parts[6] : 0;
|
||||
if (parts[0] < 1 || parts[0] > 9999) return null;
|
||||
if (nanos < 0 || nanos >= 1000000000) return null;
|
||||
final result = DateTime(
|
||||
parts[0],
|
||||
parts[1],
|
||||
parts[2],
|
||||
parts[3],
|
||||
parts[4],
|
||||
parts[5],
|
||||
nanos ~/ 1000000,
|
||||
(nanos ~/ 1000) % 1000,
|
||||
);
|
||||
if (result.year != parts[0] ||
|
||||
result.month != parts[1] ||
|
||||
result.day != parts[2] ||
|
||||
result.hour != parts[3] ||
|
||||
result.minute != parts[4] ||
|
||||
result.second != parts[5]) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return DeviceAlarm(
|
||||
// 0 仅代表未提供服务端 ID;不会作为处理接口的参数。
|
||||
id: id ?? 0,
|
||||
alarmNo: text('alarmNo'),
|
||||
title: text('alarmTitle'),
|
||||
content: text('alarmContent'),
|
||||
deviceId: text('deviceId'),
|
||||
deviceName: text('deviceName'),
|
||||
level: text('alarmLevel'),
|
||||
type: text('alarmType'),
|
||||
timeValues: text('timeValues'),
|
||||
alarmTime: time('alarmTime'),
|
||||
recoverTime: time('recoverTime'),
|
||||
handleStatus: int.tryParse(text('handleStatus')) ?? 1,
|
||||
rootCause: text('rootCause'),
|
||||
handleSuggestion: text('handleSuggestion'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/device_alarm.dart';
|
||||
import '../../domain/repositories/device_alarm_repository.dart';
|
||||
import '../datasources/device_alarm_mqtt_datasource.dart';
|
||||
import '../datasources/device_alarm_remote_datasource.dart';
|
||||
|
||||
class DeviceAlarmRepositoryImpl implements DeviceAlarmRepository {
|
||||
const DeviceAlarmRepositoryImpl(this.mqtt, this.remote);
|
||||
final DeviceAlarmMqttDataSource mqtt;
|
||||
final DeviceAlarmRemoteDataSource remote;
|
||||
|
||||
@override
|
||||
Stream<List<DeviceAlarm>> watch(String deviceCode) => mqtt.watch(deviceCode);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Unit>> handle(int alarmId) async {
|
||||
try {
|
||||
await remote.handle(alarmId);
|
||||
return const Right(unit);
|
||||
} on DeviceAlarmRemoteException catch (error) {
|
||||
debugPrint('[设备告警] 处理被拒绝 alarmId=$alarmId msg=${error.message}');
|
||||
return Left(ServerFailure(error.message));
|
||||
} on DioException catch (error) {
|
||||
debugPrint(
|
||||
'[设备告警] 处理请求异常 alarmId=$alarmId type=${error.type} msg=${error.message}',
|
||||
);
|
||||
final body = error.response?.data;
|
||||
return Left(
|
||||
NetworkFailure(body is Map ? body['msg']?.toString() ?? '' : ''),
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint('[设备告警] 处理失败 alarmId=$alarmId error=$error');
|
||||
return Left(Failure(''));
|
||||
}
|
||||
}
|
||||
}
|
||||
90
lib/features/device_alarms/domain/entities/device_alarm.dart
Normal file
90
lib/features/device_alarms/domain/entities/device_alarm.dart
Normal file
@@ -0,0 +1,90 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// 设备故障与预警记录;关闭是业务处理状态,不代表设备故障已经恢复。
|
||||
class DeviceAlarm extends Equatable {
|
||||
const DeviceAlarm({
|
||||
required this.id,
|
||||
this.alarmNo = '',
|
||||
this.title = '',
|
||||
this.content = '',
|
||||
this.deviceId = '',
|
||||
this.deviceName = '',
|
||||
this.sourceSn = '',
|
||||
this.level = '',
|
||||
this.type = '',
|
||||
this.timeValues = '',
|
||||
this.alarmTime,
|
||||
this.recoverTime,
|
||||
this.handleStatus = 1,
|
||||
this.rootCause = '',
|
||||
this.handleSuggestion = '',
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String alarmNo;
|
||||
final String title;
|
||||
final String content;
|
||||
final String deviceId;
|
||||
final String deviceName;
|
||||
|
||||
/// 由订阅 Topic 标记来源;后端 deviceId 可能是数据库 ID。
|
||||
final String sourceSn;
|
||||
final String level;
|
||||
final String type;
|
||||
final String timeValues;
|
||||
final DateTime? alarmTime;
|
||||
final DateTime? recoverTime;
|
||||
final int handleStatus;
|
||||
final String rootCause;
|
||||
final String handleSuggestion;
|
||||
|
||||
bool get isClosed => handleStatus == 2;
|
||||
|
||||
/// 无服务端 ID 的推送仍可展示,按来源/故障码/发生时间标识,避免多条 id:null 互相覆盖。
|
||||
String get recordKey => id > 0
|
||||
? 'id:$id'
|
||||
: 'push:${sourceSn.isEmpty ? deviceId : sourceSn}|$alarmNo|${alarmTime?.toIso8601String() ?? ''}';
|
||||
|
||||
DeviceAlarm closed() => copyWith(handleStatus: 2);
|
||||
|
||||
DeviceAlarm copyWith({
|
||||
String? sourceSn,
|
||||
String? deviceName,
|
||||
int? handleStatus,
|
||||
}) => DeviceAlarm(
|
||||
id: id,
|
||||
alarmNo: alarmNo,
|
||||
title: title,
|
||||
content: content,
|
||||
deviceId: deviceId,
|
||||
deviceName: deviceName ?? this.deviceName,
|
||||
sourceSn: sourceSn ?? this.sourceSn,
|
||||
level: level,
|
||||
type: type,
|
||||
timeValues: timeValues,
|
||||
alarmTime: alarmTime,
|
||||
recoverTime: recoverTime,
|
||||
handleStatus: handleStatus ?? this.handleStatus,
|
||||
rootCause: rootCause,
|
||||
handleSuggestion: handleSuggestion,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
alarmNo,
|
||||
title,
|
||||
content,
|
||||
deviceId,
|
||||
deviceName,
|
||||
sourceSn,
|
||||
level,
|
||||
type,
|
||||
timeValues,
|
||||
alarmTime,
|
||||
recoverTime,
|
||||
handleStatus,
|
||||
rootCause,
|
||||
handleSuggestion,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/// Topic 使用设备 SN,与告警记录里的设备数据库 ID 分开。
|
||||
class DeviceAlarmTarget {
|
||||
const DeviceAlarmTarget({
|
||||
required this.sn,
|
||||
required this.name,
|
||||
this.deviceId = '',
|
||||
});
|
||||
final String sn;
|
||||
final String name;
|
||||
final String deviceId;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/device_alarm.dart';
|
||||
|
||||
abstract class DeviceAlarmRepository {
|
||||
Stream<List<DeviceAlarm>> watch(String deviceCode);
|
||||
Future<Either<Failure, Unit>> handle(int alarmId);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/device_alarm.dart';
|
||||
import '../repositories/device_alarm_repository.dart';
|
||||
|
||||
class WatchDeviceAlarmsUseCase {
|
||||
const WatchDeviceAlarmsUseCase(this.repository);
|
||||
final DeviceAlarmRepository repository;
|
||||
|
||||
Stream<List<DeviceAlarm>> call(String deviceCode) =>
|
||||
repository.watch(deviceCode.trim());
|
||||
}
|
||||
|
||||
class HandleDeviceAlarmUseCase {
|
||||
const HandleDeviceAlarmUseCase(this.repository);
|
||||
final DeviceAlarmRepository repository;
|
||||
|
||||
Future<Either<Failure, Unit>> call(int alarmId) async {
|
||||
if (alarmId <= 0) return Left(Failure(''));
|
||||
return repository.handle(alarmId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../../../v2/device_list/domain/usecases/get_site_devices_usecase.dart';
|
||||
import '../entities/device_alarm_target.dart';
|
||||
|
||||
/// 使用完整场站设备列表,不受页面筛选或设备在线状态影响。
|
||||
class LoadSiteAlarmTargetsUseCase {
|
||||
const LoadSiteAlarmTargetsUseCase(this.getSiteDevices);
|
||||
final GetSiteDevicesUseCase getSiteDevices;
|
||||
|
||||
Future<List<DeviceAlarmTarget>> call(int siteId) async {
|
||||
final devices = await getSiteDevices(siteId);
|
||||
final targets = <String, DeviceAlarmTarget>{};
|
||||
for (final device in devices) {
|
||||
final sn = device.name.trim();
|
||||
// 场站接口可能缺少型号/类型,不能用 UI 的 isRobot 推断过滤订阅目标。
|
||||
// 按真实场站设备 SN 建立告警订阅,保留空 SN 和跨场站保护。
|
||||
if (sn.isEmpty || (device.siteId != null && device.siteId != siteId)) {
|
||||
continue;
|
||||
}
|
||||
final alias = device.deviceAlias?.trim() ?? '';
|
||||
targets[sn] = DeviceAlarmTarget(
|
||||
sn: sn,
|
||||
name: alias.isEmpty ? sn : alias,
|
||||
deviceId: device.deviceId,
|
||||
);
|
||||
}
|
||||
return List.unmodifiable(targets.values);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../v2/waring_center/domain/entities/alarm_entity.dart';
|
||||
import '../../../v2/waring_center/domain/usecases/get_alarm_list_usecase.dart';
|
||||
|
||||
class DeviceAlarmHistoryState extends Equatable {
|
||||
const DeviceAlarmHistoryState({
|
||||
this.alarms = const [],
|
||||
this.isLoading = false,
|
||||
this.isLoadingMore = false,
|
||||
this.hasMore = true,
|
||||
this.error,
|
||||
});
|
||||
final List<AlarmEntity> alarms;
|
||||
final bool isLoading;
|
||||
final bool isLoadingMore;
|
||||
final bool hasMore;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [alarms, isLoading, isLoadingMore, hasMore, error];
|
||||
}
|
||||
|
||||
/// 复用旧告警列表用例;设备历史按原始设备标识筛选,分页依据服务器原始条数。
|
||||
class DeviceAlarmHistoryCubit extends Cubit<DeviceAlarmHistoryState> {
|
||||
DeviceAlarmHistoryCubit(
|
||||
this.getAlarms, {
|
||||
required this.siteId,
|
||||
this.deviceSn,
|
||||
this.deviceId,
|
||||
}) : super(const DeviceAlarmHistoryState());
|
||||
|
||||
final GetAlarmListUseCase getAlarms;
|
||||
final int siteId;
|
||||
final String? deviceSn;
|
||||
final String? deviceId;
|
||||
static const pageSize = 20;
|
||||
final _records = <String, AlarmEntity>{};
|
||||
int _page = 0;
|
||||
int _version = 0;
|
||||
int? _failedPage;
|
||||
|
||||
Future<void> refresh() async {
|
||||
++_version;
|
||||
await _load(1);
|
||||
}
|
||||
|
||||
Future<void> loadMore() async {
|
||||
if (state.isLoading ||
|
||||
state.isLoadingMore ||
|
||||
!state.hasMore ||
|
||||
state.error != null) {
|
||||
return;
|
||||
}
|
||||
await _load(_page + 1);
|
||||
}
|
||||
|
||||
Future<void> retry() async {
|
||||
if (state.isLoading || state.isLoadingMore || _failedPage == null) return;
|
||||
await _load(_failedPage!);
|
||||
}
|
||||
|
||||
Future<void> _load(int page) async {
|
||||
if (isClosed) return;
|
||||
final version = _version;
|
||||
emit(
|
||||
DeviceAlarmHistoryState(
|
||||
alarms: state.alarms,
|
||||
isLoading: page == 1,
|
||||
isLoadingMore: page > 1,
|
||||
hasMore: state.hasMore,
|
||||
),
|
||||
);
|
||||
debugPrintSynchronously(
|
||||
'[设备告警][HISTORY_REQUEST] site=$siteId SN=$deviceSn deviceId=$deviceId page=$page pageSize=$pageSize',
|
||||
);
|
||||
try {
|
||||
final result = await getAlarms(
|
||||
siteId: siteId,
|
||||
page: page,
|
||||
pageSize: pageSize,
|
||||
);
|
||||
if (isClosed || version != _version) return;
|
||||
result.fold((failure) => _failed(failure.message, page), (rows) {
|
||||
_failedPage = null;
|
||||
if (page == 1) _records.clear();
|
||||
final oldCount = _records.length;
|
||||
for (final alarm in rows) {
|
||||
if (alarm.siteId == null || alarm.siteId == siteId) {
|
||||
_records[alarm.id] = alarm;
|
||||
}
|
||||
}
|
||||
_page = page;
|
||||
final scoped = _records.values.where((alarm) {
|
||||
if (deviceSn == null) return true;
|
||||
return alarm.device == deviceSn ||
|
||||
alarm.deviceId == deviceSn ||
|
||||
(deviceId != null &&
|
||||
deviceId!.isNotEmpty &&
|
||||
alarm.deviceId == deviceId);
|
||||
}).toList()..sort((a, b) => b.time.compareTo(a.time));
|
||||
debugPrintSynchronously(
|
||||
'[设备告警][HISTORY_RESULT] site=$siteId SN=$deviceSn page=$page raw=${rows.length} scoped=${scoped.length}',
|
||||
);
|
||||
emit(
|
||||
DeviceAlarmHistoryState(
|
||||
alarms: List.unmodifiable(scoped),
|
||||
hasMore:
|
||||
rows.length >= pageSize &&
|
||||
(page == 1 || _records.length > oldCount),
|
||||
),
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isClosed && version == _version) _failed('$error', page);
|
||||
}
|
||||
}
|
||||
|
||||
void _failed(String message, int page) {
|
||||
_failedPage = page;
|
||||
debugPrintSynchronously(
|
||||
'[设备告警][HISTORY_ERROR] site=$siteId error=$message',
|
||||
);
|
||||
emit(
|
||||
DeviceAlarmHistoryState(
|
||||
alarms: state.alarms,
|
||||
hasMore: state.hasMore,
|
||||
error: message,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../../domain/entities/device_alarm.dart';
|
||||
|
||||
/// 所有设备与单设备展示只是对场站共享数据的不同投影。
|
||||
class DeviceAlarmsState extends Equatable {
|
||||
const DeviceAlarmsState({
|
||||
this.siteId,
|
||||
this.isLoading = false,
|
||||
this.loadFailed = false,
|
||||
this.alarms = const [],
|
||||
this.deviceSns = const {},
|
||||
this.receivedSns = const {},
|
||||
this.failedSns = const {},
|
||||
this.handlingIds = const {},
|
||||
this.handleErrors = const {},
|
||||
this.closedIds = const {},
|
||||
});
|
||||
|
||||
final int? siteId;
|
||||
final bool isLoading;
|
||||
final bool loadFailed;
|
||||
final List<DeviceAlarm> alarms;
|
||||
final Set<String> deviceSns;
|
||||
final Set<String> receivedSns;
|
||||
final Set<String> failedSns;
|
||||
final Set<int> handlingIds;
|
||||
final Map<int, String> handleErrors;
|
||||
final Set<int> closedIds;
|
||||
|
||||
bool get hasReceived =>
|
||||
siteId != null &&
|
||||
!isLoading &&
|
||||
!loadFailed &&
|
||||
deviceSns.every(receivedSns.contains);
|
||||
bool get subscriptionFailed => loadFailed || failedSns.isNotEmpty;
|
||||
int get pendingCount => alarms.where((alarm) => !alarm.isClosed).length;
|
||||
|
||||
DeviceAlarmsState forDevice(String? deviceSn) {
|
||||
if (deviceSn == null) return this;
|
||||
final sn = deviceSn.trim();
|
||||
final records = alarms.where((alarm) => alarm.sourceSn == sn).toList();
|
||||
final ids = records.map((alarm) => alarm.id).toSet();
|
||||
return copyWith(
|
||||
alarms: List.unmodifiable(records),
|
||||
deviceSns: Set.unmodifiable({sn}),
|
||||
receivedSns: Set.unmodifiable(receivedSns.where((value) => value == sn)),
|
||||
failedSns: Set.unmodifiable(failedSns.where((value) => value == sn)),
|
||||
handlingIds: Set.unmodifiable(handlingIds.intersection(ids)),
|
||||
handleErrors: Map.unmodifiable({
|
||||
for (final entry in handleErrors.entries)
|
||||
if (ids.contains(entry.key)) entry.key: entry.value,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
DeviceAlarmsState copyWith({
|
||||
bool? isLoading,
|
||||
bool? loadFailed,
|
||||
List<DeviceAlarm>? alarms,
|
||||
Set<String>? deviceSns,
|
||||
Set<String>? receivedSns,
|
||||
Set<String>? failedSns,
|
||||
Set<int>? handlingIds,
|
||||
Map<int, String>? handleErrors,
|
||||
Set<int>? closedIds,
|
||||
}) => DeviceAlarmsState(
|
||||
siteId: siteId,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
loadFailed: loadFailed ?? this.loadFailed,
|
||||
alarms: alarms ?? this.alarms,
|
||||
deviceSns: deviceSns ?? this.deviceSns,
|
||||
receivedSns: receivedSns ?? this.receivedSns,
|
||||
failedSns: failedSns ?? this.failedSns,
|
||||
handlingIds: handlingIds ?? this.handlingIds,
|
||||
handleErrors: handleErrors ?? this.handleErrors,
|
||||
closedIds: closedIds ?? this.closedIds,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
siteId,
|
||||
isLoading,
|
||||
loadFailed,
|
||||
alarms,
|
||||
deviceSns,
|
||||
receivedSns,
|
||||
failedSns,
|
||||
handlingIds,
|
||||
handleErrors,
|
||||
closedIds,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrintSynchronously;
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import 'device_alarm_history_tab.dart';
|
||||
import 'device_alarm_realtime_list.dart';
|
||||
|
||||
Future<void> showDeviceAlarmDialog(
|
||||
BuildContext context, {
|
||||
required DeviceAlarmsCubit cubit,
|
||||
String? deviceSn,
|
||||
}) {
|
||||
unawaited(cubit.ensureSubscriptions(deviceSn: deviceSn));
|
||||
debugPrintSynchronously(
|
||||
'[设备告警] 打开底部面板 site=${cubit.state.siteId} scope=${deviceSn ?? '当前场站全部车辆'} records=${cubit.state.forDevice(deviceSn).alarms.length}',
|
||||
);
|
||||
return showModalBottomSheet<void>(
|
||||
context: context,
|
||||
useRootNavigator: true,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
showDragHandle: true,
|
||||
backgroundColor: const Color(0xFFF6FAFE),
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
builder: (_) => DeviceAlarmDialog(cubit: cubit, deviceSn: deviceSn),
|
||||
);
|
||||
}
|
||||
|
||||
/// 实时与历史共用场站范围及最新处理状态,各自维护展示/加载组件。
|
||||
class DeviceAlarmDialog extends StatelessWidget {
|
||||
const DeviceAlarmDialog({super.key, required this.cubit, this.deviceSn});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String? deviceSn;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return SafeArea(
|
||||
top: false,
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
height: MediaQuery.sizeOf(context).height * 0.72,
|
||||
child: DefaultTabController(
|
||||
length: 2,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.translate(
|
||||
deviceSn == null
|
||||
? 'device_alarms.site_title'
|
||||
: 'device_detail_v2.rec_fault_title',
|
||||
),
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Color(0xFF1A2B4A),
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: l10n.translate('common.close'),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
TabBar(
|
||||
labelColor: const Color(0xFF1C96F6),
|
||||
tabs: [
|
||||
Tab(text: l10n.translate('device_alarms.realtime')),
|
||||
Tab(text: l10n.translate('device_alarms.history')),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
children: [
|
||||
DeviceAlarmRealtimeList(cubit: cubit, deviceSn: deviceSn),
|
||||
DeviceAlarmHistoryTab(cubit: cubit, deviceSn: deviceSn),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import '../cubit/device_alarms_state.dart';
|
||||
|
||||
/// 历史卡片和旧详情页共用最新处理入口,统一共享进行中/失败/关闭状态。
|
||||
class DeviceAlarmHistoryAction extends StatelessWidget {
|
||||
const DeviceAlarmHistoryAction({
|
||||
super.key,
|
||||
required this.cubit,
|
||||
required this.alarmId,
|
||||
required this.siteId,
|
||||
required this.isPending,
|
||||
this.onHandled,
|
||||
this.compact = true,
|
||||
});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String alarmId;
|
||||
final int siteId;
|
||||
final bool isPending;
|
||||
final VoidCallback? onHandled;
|
||||
final bool compact;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final id = int.tryParse(alarmId);
|
||||
return BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, state) {
|
||||
final closed = !isPending || state.closedIds.contains(id);
|
||||
final handling = state.handlingIds.contains(id);
|
||||
final stale = state.siteId != siteId;
|
||||
final error = state.handleErrors[id];
|
||||
final action = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
key: ValueKey('history-handle-$alarmId'),
|
||||
onPressed: id == null || id <= 0 || closed || handling || stale
|
||||
? null
|
||||
: () async {
|
||||
await cubit.handle(id, historySiteId: siteId);
|
||||
if (context.mounted &&
|
||||
cubit.state.siteId == siteId &&
|
||||
cubit.state.closedIds.contains(id)) {
|
||||
onHandled?.call();
|
||||
}
|
||||
},
|
||||
child: handling
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(
|
||||
l10n.translate(
|
||||
closed
|
||||
? 'device_alarms.closed'
|
||||
: 'device_alarms.go_handle',
|
||||
),
|
||||
),
|
||||
),
|
||||
if (error != null || stale)
|
||||
SizedBox(
|
||||
width: compact ? 140 : double.infinity,
|
||||
child: Text(
|
||||
stale
|
||||
? l10n.translate('device_alarms.site_changed')
|
||||
: error!.isEmpty
|
||||
? l10n.translate('device_alarms.handle_failed')
|
||||
: error,
|
||||
style: const TextStyle(color: Colors.red, fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
return compact
|
||||
? action
|
||||
: SafeArea(
|
||||
top: false,
|
||||
child: Container(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
padding: const EdgeInsets.all(16),
|
||||
width: double.infinity,
|
||||
child: action,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../../../v2/waring_center/domain/entities/alarm_entity.dart';
|
||||
import '../../../v2/waring_center/domain/usecases/get_alarm_list_usecase.dart';
|
||||
import '../../../v2/waring_center/presentation/bloc/alarm_detail_cubit.dart';
|
||||
import '../../../v2/waring_center/presentation/constants/alarm_constants.dart';
|
||||
import '../../../v2/waring_center/presentation/pages/alarm_detail_page.dart';
|
||||
import '../../../v2/waring_center/presentation/widgets/alarm_item_card.dart';
|
||||
import '../cubit/device_alarm_history_cubit.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import '../cubit/device_alarms_state.dart';
|
||||
import 'device_alarm_history_action.dart';
|
||||
|
||||
class DeviceAlarmHistoryTab extends StatelessWidget {
|
||||
const DeviceAlarmHistoryTab({super.key, required this.cubit, this.deviceSn});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String? deviceSn;
|
||||
|
||||
@override
|
||||
Widget build(
|
||||
BuildContext context,
|
||||
) => BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, state) {
|
||||
final siteId = state.siteId;
|
||||
if (siteId == null) {
|
||||
return Center(
|
||||
child: Text(
|
||||
AppLocalizations.of(context).translate('device_alarms.select_site'),
|
||||
),
|
||||
);
|
||||
}
|
||||
final deviceId = deviceSn == null ? null : cubit.deviceIdForSn(deviceSn!);
|
||||
return BlocProvider(
|
||||
key: ValueKey((siteId, deviceSn, deviceId)),
|
||||
create: (_) => DeviceAlarmHistoryCubit(
|
||||
GetIt.I<GetAlarmListUseCase>(),
|
||||
siteId: siteId,
|
||||
deviceSn: deviceSn,
|
||||
deviceId: deviceId,
|
||||
)..refresh(),
|
||||
child: _HistoryList(cubit: cubit, siteId: siteId),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _HistoryList extends StatelessWidget {
|
||||
const _HistoryList({required this.cubit, required this.siteId});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final int siteId;
|
||||
|
||||
void _openDetail(BuildContext context, AlarmEntity alarm) {
|
||||
Navigator.of(context, rootNavigator: true).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => BlocProvider(
|
||||
create: (_) => GetIt.I<AlarmDetailCubit>(),
|
||||
child: AlarmDetailPage(
|
||||
alarmId: alarm.id,
|
||||
actionBuilder: (detailContext, detail) => DeviceAlarmHistoryAction(
|
||||
cubit: cubit,
|
||||
alarmId: alarm.id,
|
||||
siteId: siteId,
|
||||
isPending:
|
||||
detail.alarmStatus == '待处理' || detail.alarmStatus == '1',
|
||||
compact: false,
|
||||
onHandled: () => detailContext
|
||||
.read<AlarmDetailCubit>()
|
||||
.loadAlarmDetail(alarm.id),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final history = context.read<DeviceAlarmHistoryCubit>();
|
||||
return BlocBuilder<DeviceAlarmHistoryCubit, DeviceAlarmHistoryState>(
|
||||
builder: (context, state) {
|
||||
if (state.isLoading && state.alarms.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return RefreshIndicator(
|
||||
onRefresh: history.refresh,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
if (state.isLoading) const LinearProgressIndicator(),
|
||||
if (state.error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 20,
|
||||
horizontal: 12,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.cloud_off_outlined,
|
||||
size: 28,
|
||||
color: Color(0xFF86909C),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
l10n.translate('device_alarms.history_failed'),
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
color: Color(0xFF5C6B84),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: history.retry,
|
||||
child: Text(l10n.translate('device_alarms.retry')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (state.alarms.isEmpty && state.error == null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 28),
|
||||
child: Center(
|
||||
child: Text(l10n.translate('device_alarms.history_empty')),
|
||||
),
|
||||
),
|
||||
for (final alarm in state.alarms)
|
||||
BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, live) {
|
||||
final closed = live.closedIds.contains(
|
||||
int.tryParse(alarm.id),
|
||||
);
|
||||
final displayed = closed
|
||||
? alarm.copyWith(status: AlarmStatus.closed)
|
||||
: alarm;
|
||||
return AlarmItemCard(
|
||||
key: ValueKey(alarm.id),
|
||||
margin: const EdgeInsets.symmetric(vertical: 6),
|
||||
alarm: displayed,
|
||||
onTap: () => _openDetail(context, displayed),
|
||||
trailing: displayed.status == AlarmStatus.pending
|
||||
? DeviceAlarmHistoryAction(
|
||||
cubit: cubit,
|
||||
alarmId: alarm.id,
|
||||
siteId: siteId,
|
||||
isPending: true,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
},
|
||||
),
|
||||
if (state.isLoadingMore)
|
||||
const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
)
|
||||
else if (state.hasMore && state.error == null && !state.isLoading)
|
||||
TextButton(
|
||||
onPressed: history.loadMore,
|
||||
child: Text(l10n.translate('device_alarms.load_more')),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
|
||||
String deviceAlarmTime(DateTime? time) {
|
||||
if (time == null) return '—';
|
||||
String two(int value) => value.toString().padLeft(2, '0');
|
||||
return '${time.year}-${two(time.month)}-${two(time.day)} '
|
||||
'${two(time.hour)}:${two(time.minute)}:${two(time.second)}';
|
||||
}
|
||||
|
||||
String deviceAlarmLevel(AppLocalizations l10n, String level) {
|
||||
if (level.toUpperCase() == 'WARNING') {
|
||||
return l10n.translate('device_alarms.level_warning');
|
||||
}
|
||||
if (const ['1', '2', '3', '4'].contains(level)) {
|
||||
return l10n.translate('device_alarms.level_$level');
|
||||
}
|
||||
return level.isEmpty ? '—' : level;
|
||||
}
|
||||
|
||||
String deviceAlarmType(AppLocalizations l10n, String type) {
|
||||
if (type.toUpperCase() == 'MOWER_FAULT') {
|
||||
return l10n.translate('device_alarms.type_mower_fault');
|
||||
}
|
||||
if (const ['1', '2', '3', '4', '5', '6'].contains(type)) {
|
||||
return l10n.translate('device_alarms.type_$type');
|
||||
}
|
||||
return type.isEmpty ? '—' : type;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import '../cubit/device_alarms_state.dart';
|
||||
import 'device_alarm_record_card.dart';
|
||||
|
||||
class DeviceAlarmRealtimeList extends StatelessWidget {
|
||||
const DeviceAlarmRealtimeList({
|
||||
super.key,
|
||||
required this.cubit,
|
||||
this.deviceSn,
|
||||
});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String? deviceSn;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, all) {
|
||||
final state = all.forDevice(deviceSn);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (state.isLoading) const LinearProgressIndicator(minHeight: 2),
|
||||
if (state.subscriptionFailed)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.translate('device_alarms.receive_failed'),
|
||||
style: const TextStyle(color: Color(0xFFF0483E)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: cubit.retry,
|
||||
child: Text(l10n.translate('device_alarms.retry')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: state.alarms.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
l10n.translate(
|
||||
state.hasReceived
|
||||
? 'device_alarms.empty'
|
||||
: 'device_alarms.waiting',
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Color(0xFF86909C)),
|
||||
),
|
||||
)
|
||||
: ListView.separated(
|
||||
itemCount: state.alarms.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
final alarm = state.alarms[index];
|
||||
return DeviceAlarmRecordCard(
|
||||
key: ValueKey(alarm.recordKey),
|
||||
alarm: alarm,
|
||||
handling: state.handlingIds.contains(alarm.id),
|
||||
error: state.handleErrors[alarm.id],
|
||||
onHandle: () => cubit.handle(alarm.id),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../../domain/entities/device_alarm.dart';
|
||||
import 'device_alarm_labels.dart';
|
||||
|
||||
/// 概览弹窗和记录弹窗共用的单条告警展示及处理入口。
|
||||
class DeviceAlarmRecordCard extends StatelessWidget {
|
||||
const DeviceAlarmRecordCard({
|
||||
super.key,
|
||||
required this.alarm,
|
||||
required this.onHandle,
|
||||
this.handling = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final DeviceAlarm alarm;
|
||||
final VoidCallback onHandle;
|
||||
final bool handling;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final color = alarm.isClosed
|
||||
? const Color(0xFF6B7280)
|
||||
: const Color(0xFFE59023);
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: const Color(0xFFE5EDF7)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
alarm.title.isEmpty
|
||||
? l10n.translate('device_alarms.untitled')
|
||||
: alarm.title,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Color(0xFF1A2B4A),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 6,
|
||||
children: [
|
||||
Text(
|
||||
l10n.translate(
|
||||
alarm.isClosed
|
||||
? 'device_alarms.closed'
|
||||
: 'device_alarms.pending',
|
||||
),
|
||||
style: TextStyle(color: color, fontWeight: FontWeight.w600),
|
||||
),
|
||||
if (alarm.level.isNotEmpty)
|
||||
Text(deviceAlarmLevel(l10n, alarm.level)),
|
||||
if (alarm.type.isNotEmpty)
|
||||
Text(deviceAlarmType(l10n, alarm.type)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_detail(
|
||||
l10n.translate('device_alarms.time'),
|
||||
deviceAlarmTime(alarm.alarmTime),
|
||||
),
|
||||
if (alarm.alarmNo.isNotEmpty)
|
||||
_detail(l10n.translate('device_alarms.number'), alarm.alarmNo),
|
||||
if (alarm.deviceName.isNotEmpty)
|
||||
_detail(l10n.translate('device_alarms.device'), alarm.deviceName),
|
||||
if (alarm.sourceSn.isNotEmpty)
|
||||
_detail(l10n.translate('device_alarms.sn'), alarm.sourceSn),
|
||||
if (alarm.content.isNotEmpty)
|
||||
_detail(l10n.translate('device_alarms.content'), alarm.content),
|
||||
if (alarm.timeValues.isNotEmpty)
|
||||
_detail(l10n.translate('device_alarms.value'), alarm.timeValues),
|
||||
if (alarm.recoverTime != null)
|
||||
_detail(
|
||||
l10n.translate('device_alarms.recover_time'),
|
||||
deviceAlarmTime(alarm.recoverTime),
|
||||
),
|
||||
if (alarm.rootCause.isNotEmpty)
|
||||
_detail(
|
||||
l10n.translate('device_alarms.root_cause'),
|
||||
alarm.rootCause,
|
||||
),
|
||||
if (alarm.handleSuggestion.isNotEmpty)
|
||||
_detail(
|
||||
l10n.translate('device_alarms.suggestion'),
|
||||
alarm.handleSuggestion,
|
||||
),
|
||||
if (error != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
error!.isEmpty
|
||||
? l10n.translate('device_alarms.handle_failed')
|
||||
: error!,
|
||||
style: const TextStyle(color: Color(0xFFF0483E), fontSize: 12),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
if (alarm.id <= 0)
|
||||
Text(
|
||||
l10n.translate('device_alarms.missing_id'),
|
||||
style: const TextStyle(fontSize: 12, color: Color(0xFF86909C)),
|
||||
)
|
||||
else
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FilledButton(
|
||||
key: ValueKey('handle-alarm-${alarm.id}'),
|
||||
onPressed: alarm.isClosed || handling ? null : onHandle,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF1C96F6),
|
||||
),
|
||||
child: handling
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
l10n.translate(
|
||||
alarm.isClosed
|
||||
? 'device_alarms.closed'
|
||||
: 'device_alarms.handle',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _detail(String label, String value) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 5),
|
||||
child: Text(
|
||||
'$label: $value',
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.5,
|
||||
color: Color(0xFF5C6B84),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import 'device_alarm_dialog.dart';
|
||||
import 'device_alarm_summary_card.dart';
|
||||
|
||||
/// 标题、右侧箭头和卡片均可打开同一设备范围的告警弹窗。
|
||||
class DeviceAlarmSection extends StatelessWidget {
|
||||
const DeviceAlarmSection({
|
||||
super.key,
|
||||
required this.cubit,
|
||||
required this.deviceSn,
|
||||
});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String deviceSn;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
InkWell(
|
||||
onTap: () =>
|
||||
showDeviceAlarmDialog(context, cubit: cubit, deviceSn: deviceSn),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('device_detail_v2.fault_state'),
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: Color(0xFF1A2B4A),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 20,
|
||||
color: Color(0xFF1C96F6),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
DeviceAlarmSummaryCard(cubit: cubit, deviceSn: deviceSn),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import '../cubit/device_alarms_state.dart';
|
||||
import 'device_alarm_dialog.dart';
|
||||
import 'device_alarm_labels.dart';
|
||||
|
||||
/// 概览故障状态与记录栏共用摘要、实时状态及弹窗入口。
|
||||
class DeviceAlarmSummaryCard extends StatelessWidget {
|
||||
const DeviceAlarmSummaryCard({super.key, required this.cubit, this.deviceSn});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
final String? deviceSn;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, all) {
|
||||
final state = all.forDevice(deviceSn);
|
||||
final latest = state.alarms.firstOrNull;
|
||||
final color = state.pendingCount > 0
|
||||
? const Color(0xFFE59023)
|
||||
: const Color(0xFF6B7280);
|
||||
final title = latest == null
|
||||
? l10n.translate(
|
||||
state.hasReceived
|
||||
? 'device_alarms.empty'
|
||||
: 'device_alarms.waiting',
|
||||
)
|
||||
: latest.title.isEmpty
|
||||
? l10n.translate('device_alarms.untitled')
|
||||
: latest.title;
|
||||
final subtitle = state.subscriptionFailed
|
||||
? l10n.translate('device_alarms.receive_failed')
|
||||
: latest == null
|
||||
? l10n.translate('device_alarms.view_records')
|
||||
: '${deviceAlarmTime(latest.alarmTime)} · ${l10n.translate('device_alarms.count', {'count': state.alarms.length, 'pending': state.pendingCount})}';
|
||||
|
||||
return Material(
|
||||
color: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: Color(0xFFE5EDF7)),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: () => showDeviceAlarmDialog(
|
||||
context,
|
||||
cubit: cubit,
|
||||
deviceSn: deviceSn,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(Icons.warning_amber_rounded, color: color),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Color(0xFF1A2B4A),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
subtitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
color: Color(0xFF86909C),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 18,
|
||||
color: Color(0xFFC9CDD4),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../cubit/device_alarms_cubit.dart';
|
||||
import '../cubit/device_alarms_state.dart';
|
||||
import 'device_alarm_dialog.dart';
|
||||
|
||||
/// 设备 Tab(含空页面/加载状态)复用的当前场站消息入口。
|
||||
class SiteAlarmButton extends StatelessWidget {
|
||||
const SiteAlarmButton({super.key, required this.cubit});
|
||||
final DeviceAlarmsCubit cubit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
BlocBuilder<DeviceAlarmsCubit, DeviceAlarmsState>(
|
||||
bloc: cubit,
|
||||
builder: (context, state) => SizedBox(
|
||||
width: 44,
|
||||
height: 44,
|
||||
child: IconButton.filledTonal(
|
||||
tooltip: AppLocalizations.of(
|
||||
context,
|
||||
).translate('device_alarms.site_title'),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: const Color(0xFF1C96F6),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
onPressed: () => showDeviceAlarmDialog(context, cubit: cubit),
|
||||
icon: Badge.count(
|
||||
count: state.pendingCount,
|
||||
isLabelVisible: state.pendingCount > 0,
|
||||
child: const Icon(Icons.notifications_none),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/site/presentation/cubit/site_cubit.dart';
|
||||
import 'pv_task_progress_content.dart';
|
||||
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -1247,114 +1251,18 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
);
|
||||
}
|
||||
|
||||
/// 作业进度卡(浅色版):进度条单独一行,面积与时长两列在下一行,
|
||||
/// 窄栏也不会因为三列硬排而拥挤。
|
||||
Widget _progressCard() {
|
||||
final tr = AppLocalizations.of(context);
|
||||
return _panel(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
tr.translate('pv_control.work_progress'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: s(PvHudType.label, 11).copyWith(
|
||||
color: PvHudColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'68%',
|
||||
style: s(PvHudType.value, 12).copyWith(
|
||||
color: PvHudColors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: d(5)),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(d(3)),
|
||||
child: LinearProgressIndicator(
|
||||
value: 0.68,
|
||||
minHeight: d(5),
|
||||
backgroundColor: PvHudColors.pill,
|
||||
valueColor: const AlwaysStoppedAnimation(PvHudColors.success),
|
||||
),
|
||||
),
|
||||
SizedBox(height: d(8)),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _progressItem(
|
||||
tr.translate('pv_control.work_area_size'),
|
||||
'2.5',
|
||||
unit: '/ 3.6 ha',
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: 1,
|
||||
height: d(24),
|
||||
color: PvHudColors.border,
|
||||
),
|
||||
Expanded(
|
||||
child: _progressItem(
|
||||
tr.translate('pv_control.work_duration'),
|
||||
'01:42:18',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
/// 作业进度来自场站共享任务状态,与自主作业使用同一数据源。
|
||||
Widget _progressCard() => _panel(
|
||||
child: BlocBuilder<SiteCubit, SiteState>(
|
||||
bloc: sl<SiteCubit>(),
|
||||
builder: (context, site) => PvTaskProgressContent(
|
||||
subscriptions: sl<SiteDeviceRealtimeSubscriptions>(),
|
||||
siteId: site.selectedSite?.id,
|
||||
deviceSn: widget.deviceSn,
|
||||
scale: _sc,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _progressItem(String label, String value, {String? unit}) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: s(PvHudType.caption, 10).copyWith(
|
||||
color: PvHudColors.textTertiary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: d(2)),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
value,
|
||||
style: s(PvHudType.value, 12).copyWith(
|
||||
color: PvHudColors.textPrimary,
|
||||
),
|
||||
),
|
||||
if (unit != null) ...[
|
||||
SizedBox(width: d(2)),
|
||||
Flexible(
|
||||
child: Text(
|
||||
unit,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: s(PvHudType.caption, 10).copyWith(
|
||||
color: PvHudColors.textTertiary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
),
|
||||
);
|
||||
|
||||
Widget _statusCard() {
|
||||
final tr = AppLocalizations.of(context);
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/mower_task_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
|
||||
import '../theme/pv_hud_theme.dart';
|
||||
|
||||
/// 遥控 HUD 的只读作业进度,复用场站订阅,不参与控制指令发送。
|
||||
class PvTaskProgressContent extends StatefulWidget {
|
||||
const PvTaskProgressContent({
|
||||
super.key,
|
||||
required this.subscriptions,
|
||||
required this.siteId,
|
||||
required this.deviceSn,
|
||||
this.scale = 1,
|
||||
});
|
||||
|
||||
final SiteDeviceRealtimeSubscriptions subscriptions;
|
||||
final int? siteId;
|
||||
final String deviceSn;
|
||||
final double scale;
|
||||
|
||||
@override
|
||||
State<PvTaskProgressContent> createState() => _PvTaskProgressContentState();
|
||||
}
|
||||
|
||||
class _PvTaskProgressContentState extends State<PvTaskProgressContent> {
|
||||
Stream<MowerTaskStatusEntity?>? _stream;
|
||||
Timer? _clock;
|
||||
|
||||
double d(double value) => value * widget.scale;
|
||||
TextStyle style(TextStyle base, double size) =>
|
||||
base.copyWith(fontSize: d(size).clamp(8.0, 24.0));
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_bind();
|
||||
// 只刷新这张小卡片的上报时间,不带动视频和摇杆重建。
|
||||
_clock = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
void _bind() {
|
||||
_stream = widget.deviceSn.trim().isEmpty
|
||||
? null
|
||||
: widget.subscriptions.watchTaskStatus(
|
||||
siteId: widget.siteId,
|
||||
deviceSn: widget.deviceSn,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant PvTaskProgressContent oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.subscriptions != widget.subscriptions ||
|
||||
oldWidget.siteId != widget.siteId ||
|
||||
oldWidget.deviceSn != widget.deviceSn) {
|
||||
_bind();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_clock?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _duration(double seconds) {
|
||||
final total = seconds.floor();
|
||||
String pad(int value) => value.toString().padLeft(2, '0');
|
||||
return '${pad(total ~/ 3600)}:${pad((total ~/ 60) % 60)}:${pad(total % 60)}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final unknown = l10n.translate('common.unknown');
|
||||
String taskLabel(String key) =>
|
||||
l10n.translate('autonomous_work.task_status.$key');
|
||||
|
||||
return StreamBuilder<MowerTaskStatusEntity?>(
|
||||
// 切换设备或场站时直接清空旧快照,不能显示上一台设备的数据。
|
||||
key: ValueKey((widget.siteId, widget.deviceSn, widget.subscriptions)),
|
||||
stream: _stream,
|
||||
builder: (context, snapshot) {
|
||||
final report = snapshot.data;
|
||||
final progress = report?.progress;
|
||||
final age = report == null
|
||||
? null
|
||||
: DateTime.now()
|
||||
.difference(report.receivedAt)
|
||||
.inSeconds
|
||||
.clamp(0, 999999);
|
||||
final stale = age != null && age >= 15;
|
||||
final warning = snapshot.hasError || stale;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.translate('pv_control.work_progress'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style(PvHudType.label, 11),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
progress == null
|
||||
? unknown
|
||||
: '${(progress * 100).toStringAsFixed(2)}%',
|
||||
style: style(PvHudType.value, 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: d(5)),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(d(3)),
|
||||
child: LinearProgressIndicator(
|
||||
value: progress ?? 0,
|
||||
minHeight: d(5),
|
||||
backgroundColor: PvHudColors.pill,
|
||||
color: warning || progress == null
|
||||
? PvHudColors.textTertiary
|
||||
: PvHudColors.success,
|
||||
),
|
||||
),
|
||||
SizedBox(height: d(8)),
|
||||
_pair(
|
||||
// 当前协议没有面积字段;不按距离/进度推算或复用演示数据。
|
||||
(l10n.translate('pv_control.work_area_size'), unknown),
|
||||
(
|
||||
l10n.translate('pv_control.work_duration'),
|
||||
report?.elapsedSeconds == null
|
||||
? unknown
|
||||
: _duration(report!.elapsedSeconds!),
|
||||
),
|
||||
),
|
||||
SizedBox(height: d(8)),
|
||||
_pair(
|
||||
(
|
||||
taskLabel('eta_s'),
|
||||
report?.etaSeconds == null
|
||||
? unknown
|
||||
: _duration(report!.etaSeconds!),
|
||||
),
|
||||
(
|
||||
taskLabel('distance_remaining'),
|
||||
report?.distanceRemaining == null
|
||||
? unknown
|
||||
: '${report!.distanceRemaining!.toStringAsFixed(2)} m',
|
||||
),
|
||||
),
|
||||
SizedBox(height: d(6)),
|
||||
Text(
|
||||
snapshot.hasError
|
||||
? taskLabel('unavailable')
|
||||
: report == null
|
||||
? taskLabel('waiting')
|
||||
: stale
|
||||
? taskLabel('stale')
|
||||
: l10n.translate('autonomous_work.task_status.updated', {
|
||||
'seconds': age,
|
||||
}),
|
||||
style: style(PvHudType.caption, 9).copyWith(
|
||||
color: warning ? PvHudColors.danger : PvHudColors.textTertiary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pair((String, String) left, (String, String) right) {
|
||||
Widget item((String, String) value) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(value.$1, style: style(PvHudType.caption, 10)),
|
||||
SizedBox(height: d(2)),
|
||||
Text(value.$2, style: style(PvHudType.value, 12)),
|
||||
],
|
||||
);
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: item(left)),
|
||||
SizedBox(width: d(8)),
|
||||
Container(width: 1, height: d(24), color: PvHudColors.border),
|
||||
SizedBox(width: d(8)),
|
||||
Expanded(child: item(right)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ abstract class DeviceRemoteDataSource {
|
||||
String? typeFilter,
|
||||
});
|
||||
Future<List<DeviceDataModel>> getAllDevices();
|
||||
Future<List<DeviceDataModel>> getSiteDevices(int siteId);
|
||||
|
||||
/// 根据拆分码(蓝牙设备名/时间戳)精确查询设备,未查到时返回 null
|
||||
Future<DeviceDataModel?> getDeviceBySpiltCode(String code);
|
||||
@@ -140,7 +141,9 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
}
|
||||
|
||||
// data 结构与 getDeviceList 的单条 row 一致,复用解析(deviceName 即 serialNumber)
|
||||
final model = _parseDeviceFromJson(Map<String, dynamic>.from(data as Map));
|
||||
final model = _parseDeviceFromJson(
|
||||
Map<String, dynamic>.from(data as Map),
|
||||
);
|
||||
debugPrint(
|
||||
'>>> [DeviceRemoteDataSource] getDeviceBySpiltCode 命中 code=$code serialNumber=${model.name}',
|
||||
);
|
||||
@@ -193,9 +196,7 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
final responseData = response.data;
|
||||
// 兼容 int / String 类型的 code(与 createDeviceTask 同样口径)
|
||||
final code = responseData['code'];
|
||||
final codeValue = code is int
|
||||
? code
|
||||
: int.tryParse(code?.toString() ?? '');
|
||||
final codeValue = code is int ? code : int.tryParse(code?.toString() ?? '');
|
||||
if (codeValue != 200) {
|
||||
throw Exception(responseData['msg'] ?? '一键寻车指令下发失败');
|
||||
}
|
||||
@@ -206,6 +207,20 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<DeviceDataModel>> getSiteDevices(int siteId) async {
|
||||
debugPrintSynchronously('[场站告警][设备列表] 请求场站完整设备列表 site=$siteId');
|
||||
final devices = await _fetchDevicesFromAPI(siteId);
|
||||
debugPrintSynchronously('[场站告警][设备列表] site=$siteId 返回=${devices.length}');
|
||||
for (final device in devices) {
|
||||
debugPrintSynchronously(
|
||||
'[场站告警][设备列表] SN=${device.name} id=${device.deviceId} '
|
||||
'isRobot=${device.isRobot} type=${device.type} site=${device.siteId}',
|
||||
);
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
|
||||
Future<List<DeviceDataModel>> _fetchDevicesFromAPI(int siteId) async {
|
||||
final response = await dio.get(
|
||||
HttpApiConsts.getSiteDeviceList,
|
||||
@@ -274,11 +289,11 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
/// 🔍 专项日志:只核查 getSiteList 返回体里是否带 productModel 字段
|
||||
/// 整体打印 row 会被截断,这里只摘取关键字段 + 型号相关候选字段
|
||||
void _logProductModel(List<dynamic> rows, {required int siteId}) {
|
||||
debugPrint('>>> [getSiteList/datasource] siteId=$siteId 返回 ${rows.length} 条');
|
||||
debugPrint(
|
||||
'>>> [getSiteList/datasource] siteId=$siteId 返回 ${rows.length} 条',
|
||||
);
|
||||
if (rows.isEmpty) {
|
||||
debugPrint(
|
||||
'>>> [getSiteList/datasource] rows 为空,无法判断 productModel 是否存在',
|
||||
);
|
||||
debugPrint('>>> [getSiteList/datasource] rows 为空,无法判断 productModel 是否存在');
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < rows.length; i++) {
|
||||
@@ -346,8 +361,9 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
const chunk = 700;
|
||||
var head = prefix;
|
||||
for (int start = 0; start < content.length; start += chunk) {
|
||||
final end =
|
||||
start + chunk < content.length ? start + chunk : content.length;
|
||||
final end = start + chunk < content.length
|
||||
? start + chunk
|
||||
: content.length;
|
||||
debugPrint('$head${content.substring(start, end)}');
|
||||
head = ' ↳ ';
|
||||
}
|
||||
@@ -405,6 +421,9 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
voltage: (json['voltage'] as num?)?.toDouble(),
|
||||
radiation: (json['radiation'] as num?)?.toDouble(),
|
||||
isRobot: isRobot,
|
||||
deviceAlias: json['deviceAlias']?.toString(),
|
||||
orgId: int.tryParse('${json['orgId']}'),
|
||||
siteId: int.tryParse('${json['siteId']}'),
|
||||
// 型号:列表每一项都展示(productModel 优先,productName 兜底)
|
||||
productName: (json['productName'] ?? '').toString(),
|
||||
productModel: (json['productModel'] ?? '').toString().trim().isEmpty
|
||||
@@ -514,7 +533,7 @@ class DeviceRemoteDataSourceImpl implements DeviceRemoteDataSource {
|
||||
status: '异常',
|
||||
power: 45.2,
|
||||
todayEnergy: 256.8,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
if (typeFilter != null && typeFilter != 'all') {
|
||||
|
||||
@@ -19,6 +19,9 @@ class DeviceDataModel {
|
||||
|
||||
/// 机型编码(如 MC700PRO)
|
||||
final String? productModel;
|
||||
final String? deviceAlias;
|
||||
final int? orgId;
|
||||
final int? siteId;
|
||||
|
||||
const DeviceDataModel({
|
||||
required this.deviceId,
|
||||
@@ -34,6 +37,9 @@ class DeviceDataModel {
|
||||
this.isRobot = false,
|
||||
this.productName = '',
|
||||
this.productModel,
|
||||
this.deviceAlias,
|
||||
this.orgId,
|
||||
this.siteId,
|
||||
});
|
||||
|
||||
/// 从 JSON 创建数据模型
|
||||
@@ -51,6 +57,9 @@ class DeviceDataModel {
|
||||
radiation: json['radiation']?.toDouble(),
|
||||
productName: (json['productName'] as String?) ?? '',
|
||||
productModel: json['productModel'] as String?,
|
||||
deviceAlias: json['deviceAlias'] as String?,
|
||||
orgId: int.tryParse('${json['orgId']}'),
|
||||
siteId: int.tryParse('${json['siteId']}'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,6 +78,9 @@ class DeviceDataModel {
|
||||
'radiation': radiation,
|
||||
'productName': productName,
|
||||
'productModel': productModel,
|
||||
'deviceAlias': deviceAlias,
|
||||
'orgId': orgId,
|
||||
'siteId': siteId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,6 +100,9 @@ class DeviceDataModel {
|
||||
isRobot: isRobot,
|
||||
productName: productName,
|
||||
productModel: productModel,
|
||||
deviceAlias: deviceAlias,
|
||||
orgId: orgId,
|
||||
siteId: siteId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,12 @@ class DeviceRepositoryImpl implements DeviceRepository {
|
||||
return dataModels.map((model) => model.toEntity()).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<DeviceEntity>> getSiteDevices(int siteId) async {
|
||||
final models = await remoteDataSource.getSiteDevices(siteId);
|
||||
return models.map((model) => model.toEntity()).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<DeviceEntity>> getAllDevices() async {
|
||||
final dataModels = await remoteDataSource.getAllDevices();
|
||||
|
||||
@@ -17,6 +17,9 @@ class DeviceEntity {
|
||||
|
||||
/// 机型编码(如 MC700PRO),列表型号展示以此为准
|
||||
final String? productModel;
|
||||
final String? deviceAlias;
|
||||
final int? orgId;
|
||||
final int? siteId;
|
||||
|
||||
const DeviceEntity({
|
||||
required this.deviceId,
|
||||
@@ -32,5 +35,8 @@ class DeviceEntity {
|
||||
this.isRobot = false,
|
||||
this.productName = '',
|
||||
this.productModel,
|
||||
this.deviceAlias,
|
||||
this.orgId,
|
||||
this.siteId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ abstract class DeviceRepository {
|
||||
Future<List<DeviceEntity>> getDeviceList({int? siteId, String? typeFilter});
|
||||
Future<List<DeviceEntity>> getAllDevices();
|
||||
|
||||
/// 严格查询场站设备,失败时不返回演示设备。
|
||||
Future<List<DeviceEntity>> getSiteDevices(int siteId);
|
||||
|
||||
/// 根据拆分码(蓝牙设备名/时间戳)精确查询设备,未查到时返回 null
|
||||
Future<DeviceEntity?> getDeviceBySpiltCode(String code);
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../entities/device_entity.dart';
|
||||
import '../repositories/device_repository.dart';
|
||||
|
||||
/// 获取真实场站设备,供绑定和指令目标选择使用。
|
||||
class GetSiteDevicesUseCase {
|
||||
const GetSiteDevicesUseCase(this.repository);
|
||||
|
||||
final DeviceRepository repository;
|
||||
|
||||
Future<List<DeviceEntity>> call(int siteId) {
|
||||
if (siteId <= 0) throw ArgumentError('请先选择场站');
|
||||
return repository.getSiteDevices(siteId);
|
||||
}
|
||||
}
|
||||
@@ -196,18 +196,18 @@ class FloatBarWidgetState extends State<FloatBarWidget> {
|
||||
_mapController = MapController();
|
||||
debugPrint('✅ [FloatBarWidget] 地图控制器已初始化');
|
||||
|
||||
// 只有在线时才启动 OSD 监听和视频流加载
|
||||
// MQTT 订阅不依赖列表在线状态,以便接收设备恢复后的上报。
|
||||
_droneOsdDataSource = sl<DroneOsdDataSource>();
|
||||
_startOsdListening();
|
||||
|
||||
// 视频流继续使用现有的在线检查。
|
||||
if (_droneTaskInfo!.isOnline) {
|
||||
debugPrint('🟢 [FloatBarWidget] 无人机在线,启动完整功能');
|
||||
|
||||
// 初始化 OSD 数据源
|
||||
_droneOsdDataSource = sl<DroneOsdDataSource>();
|
||||
_startOsdListening();
|
||||
|
||||
// 加载视频流
|
||||
_loadVideoStream();
|
||||
} else {
|
||||
debugPrint('⚠️ [FloatBarWidget] 无人机离线,不启动 OSD 监听和视频流');
|
||||
debugPrint('⚠️ [FloatBarWidget] 无人机离线,保留 OSD 监听,暂不加载视频流');
|
||||
|
||||
setState(() {
|
||||
_videoError = '无人机离线,无视频信号';
|
||||
|
||||
@@ -9,6 +9,10 @@ import 'package:maibu_satabot_v2/features/pv_control/presentation/pages/pv_contr
|
||||
import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_work_map.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../../device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import '../../../../device_alarms/presentation/widgets/device_alarm_dialog.dart';
|
||||
import '../../../../device_alarms/presentation/widgets/device_alarm_section.dart';
|
||||
import '../../../../device_alarms/presentation/widgets/device_alarm_summary_card.dart';
|
||||
import '../../../../device_control_mode/domain/entities/device_control_mode.dart';
|
||||
import '../../../../device_control_mode/presentation/widgets/control_mode_entry_gate.dart';
|
||||
import '../../../../devices/domain/entities/device_entity.dart';
|
||||
@@ -49,7 +53,7 @@ import 'route_editor_page_v2.dart';
|
||||
/// 仍跳 RobotControlPage,跳转前置(setTargetDevice + robotMap)与旧直进分支逐行一致,方便新旧对照。
|
||||
///
|
||||
/// 数据口径:在线态/电量/任务用接口真值(与列表卡同一口径,不造假);
|
||||
/// 后端暂未返回的字段(GNSS/割刀/故障等)显示 --,版本/位置用 DeviceV2Display 稳定占位。
|
||||
/// 后端暂未返回的字段(GNSS/割刀等)显示 --,版本/位置用 DeviceV2Display 稳定占位。
|
||||
class DeviceDetailPageV2 extends StatefulWidget {
|
||||
final RobotDataModel robot;
|
||||
|
||||
@@ -121,7 +125,7 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
static const _danger = Color(0xFFF0483E);
|
||||
static const _tabKeys = [
|
||||
'tab_overview',
|
||||
// 'tab_monitor', // 上架版暂时隐藏监测分栏。
|
||||
'tab_monitor',
|
||||
'tab_control',
|
||||
'tab_record',
|
||||
'tab_settings',
|
||||
@@ -129,6 +133,17 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
|
||||
String _tabKey = 'tab_overview';
|
||||
bool _modeDialogOpen = false;
|
||||
late final DeviceAlarmsCubit _alarmsCubit;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 进入详情即订阅,不依赖切换设备或进入控制页。
|
||||
final sn = widget.robot.name.trim();
|
||||
GetIt.I<DeviceStatusBloc>().startMqttRealtimeListening(sn);
|
||||
_alarmsCubit = GetIt.I<DeviceAlarmsCubit>();
|
||||
_alarmsCubit.logSnapshot('进入设备详情', deviceSn: sn);
|
||||
}
|
||||
|
||||
/// 当前机型的版本(来自列表接口 productModel);null/空串时为 unknown
|
||||
DeviceEdition get _edition => widget.robot.modelInfo.edition;
|
||||
@@ -574,7 +589,7 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
);
|
||||
}
|
||||
|
||||
// ===== 概览:运行概况六宫格(数据取自「设备数据监控」,点击弹原弹窗) =====
|
||||
// ===== 概览:运行概况(数据取自「设备数据监控」,点击弹原弹窗) =====
|
||||
Widget _buildOverviewSection() {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return BlocBuilder<DeviceStatusBloc, DeviceStatusState>(
|
||||
@@ -1147,10 +1162,7 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
),
|
||||
const Spacer(),
|
||||
GestureDetector(
|
||||
onTap: () => CapsuleToast.show(
|
||||
l10n.translate('device_list_v2.feature_todo'),
|
||||
showCheck: false,
|
||||
),
|
||||
onTap: _showFaultRecords,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -1970,109 +1982,14 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFaultRecordCard() {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return GestureDetector(
|
||||
onTap: _showFaultRecords,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE5EDF7)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: _offlineBg,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.warning_amber_rounded,
|
||||
size: 20,
|
||||
color: _offlineGray,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.translate('robot_fault_v2.empty'),
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: _gray,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Icon(Icons.chevron_right, size: 18, color: Color(0xFFC9CDD4)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Widget _buildFaultRecordCard() =>
|
||||
DeviceAlarmSummaryCard(cubit: _alarmsCubit, deviceSn: widget.robot.name);
|
||||
|
||||
void _showFaultRecords() {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
backgroundColor: Colors.white,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
builder: (sheetContext) => SafeArea(
|
||||
top: false,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 6, 16, 32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.translate('device_detail_v2.rec_fault_title'),
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _navy,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: l10n.translate('common.close'),
|
||||
onPressed: () => Navigator.of(sheetContext).pop(),
|
||||
icon: const Icon(Icons.close_rounded, color: _navy),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: _offlineBg,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.receipt_long_outlined,
|
||||
color: _offlineGray,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
l10n.translate('robot_fault_v2.empty'),
|
||||
style: const TextStyle(fontSize: 14, color: _gray),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
showDeviceAlarmDialog(
|
||||
context,
|
||||
cubit: _alarmsCubit,
|
||||
deviceSn: widget.robot.name,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2488,70 +2405,8 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
];
|
||||
}
|
||||
|
||||
// 故障详情接口接入前使用占位文案。
|
||||
Widget _buildFaultSection() {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
l10n.translate('device_detail_v2.fault_state'),
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _navy,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE5EDF7)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: _offlineBg,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.info_outline,
|
||||
size: 22,
|
||||
color: _offlineGray,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.translate('device_detail_v2.fault_none'),
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _navy,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
l10n.translate('device_detail_v2.fault_none_sub'),
|
||||
style: const TextStyle(fontSize: 12, color: _gray),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
Widget _buildFaultSection() =>
|
||||
DeviceAlarmSection(cubit: _alarmsCubit, deviceSn: widget.robot.name);
|
||||
|
||||
Widget _buildFunctionSection() => DeviceQuickActions(
|
||||
preferences: GetIt.I<SharedPreferences>(),
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import 'dart:async';
|
||||
import '../../../../autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
import 'package:flutter/foundation.dart' show debugPrintSynchronously;
|
||||
import '../../../../device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import '../../../../device_alarms/presentation/widgets/site_alarm_button.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -93,7 +97,10 @@ class DeviceStatusViewV2 extends StatefulWidget {
|
||||
State<DeviceStatusViewV2> createState() => _DeviceStatusViewV2State();
|
||||
}
|
||||
|
||||
class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
class _DeviceStatusViewV2State extends State<DeviceStatusViewV2>
|
||||
with AutomaticKeepAliveClientMixin {
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
final _searchController = TextEditingController();
|
||||
final _v2SearchController = TextEditingController();
|
||||
final _v2SearchFocus = FocusNode();
|
||||
@@ -103,6 +110,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
|
||||
/// 当前缓存的 siteId,用于判断是否真的发生了变化
|
||||
int? _currentSiteId;
|
||||
late final DeviceAlarmsCubit _alarmsCubit;
|
||||
late final SiteDeviceRealtimeSubscriptions _realtimeSubscriptions;
|
||||
bool _hasEntered = false;
|
||||
|
||||
/// 🔥 下拉刷新计数器:变更时联动重建"全部"标签下的机器人/无人机场内嵌列表,
|
||||
/// 使其与统计卡片(DeviceStatusBloc)同步刷新,避免统计数字与实际卡片对不上
|
||||
@@ -111,6 +121,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_alarmsCubit = sl<DeviceAlarmsCubit>();
|
||||
_realtimeSubscriptions = sl<SiteDeviceRealtimeSubscriptions>();
|
||||
_hasEntered = widget.isActive;
|
||||
final siteCubit = sl<SiteCubit>();
|
||||
final roleKey = sl<AppUserCubit>().state.user?.roleKey;
|
||||
|
||||
@@ -131,20 +144,63 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
siteCubit.selectSite(firstSite);
|
||||
}
|
||||
_currentSiteId = sl<SiteCubit>().state.selectedSite?.id;
|
||||
debugPrintSynchronously(
|
||||
'[场站告警][设备Tab] 初始化 active=${widget.isActive} site=$_currentSiteId',
|
||||
);
|
||||
if (_hasEntered) _ensureRealtimeSubscriptions('首次进入设备页');
|
||||
_siteSub = sl<SiteCubit>().stream.listen((siteState) {
|
||||
if (!mounted) return;
|
||||
final newSiteId = siteState.selectedSite?.id;
|
||||
// 只有 siteId 真正变化时才刷新(避免无意义的重复请求)
|
||||
if (newSiteId != _currentSiteId) {
|
||||
_currentSiteId = newSiteId;
|
||||
if (_hasEntered) {
|
||||
unawaited(_realtimeSubscriptions.ensureSubscriptions(newSiteId));
|
||||
}
|
||||
_refreshCurrentTabForSiteChange(newSiteId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant DeviceStatusViewV2 oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
debugPrintSynchronously(
|
||||
'[场站告警][设备Tab] 可见状态 old=${oldWidget.isActive} new=${widget.isActive} site=$_currentSiteId',
|
||||
);
|
||||
if (widget.isActive) {
|
||||
_ensureRealtimeSubscriptions(
|
||||
oldWidget.isActive ? '设备页重新显示' : '切回设备Tab',
|
||||
refresh: !oldWidget.isActive,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _ensureRealtimeSubscriptions(String reason, {bool refresh = false}) {
|
||||
final siteId = sl<SiteCubit>().state.selectedSite?.id;
|
||||
debugPrintSynchronously(
|
||||
'[场站订阅][ENTRY] $reason active=${widget.isActive} site=$siteId',
|
||||
);
|
||||
if (!widget.isActive) return;
|
||||
_hasEntered = true;
|
||||
unawaited(_realtimeSubscriptions.ensureSubscriptions(siteId, refresh: refresh));
|
||||
}
|
||||
|
||||
@override
|
||||
void reassemble() {
|
||||
super.reassemble();
|
||||
// 热重载保留 State,不能只依赖 initState 启动和输出订阅。
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && widget.isActive) {
|
||||
_ensureRealtimeSubscriptions('热重载后检查设备页订阅', refresh: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_siteSub?.cancel();
|
||||
if (_hasEntered) unawaited(_realtimeSubscriptions.ensureSubscriptions(null));
|
||||
_searchController.dispose();
|
||||
_v2SearchController.dispose();
|
||||
_v2SearchFocus.dispose();
|
||||
@@ -224,6 +280,7 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 无设备页/卡片总览均为固定浅色设计,状态栏图标须恒为深色;
|
||||
super.build(context);
|
||||
// 若跟随深色主题给白色图标,会消失在浅蓝背景上。
|
||||
final blocState = context.watch<DeviceListBloc.DeviceStatusBloc>().state;
|
||||
final fixedLightUi =
|
||||
@@ -264,7 +321,7 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
// 无设备:该场站设备接口返回空时,整页(含顶栏)切换到
|
||||
// 「01_无设备首页」设计稿页面;逻辑链保持 场站→siteId→设备列表 不变。
|
||||
if (_isNoDeviceState(state)) {
|
||||
return const NoDevicePageV2();
|
||||
return NoDevicePageV2(alarmsCubit: _alarmsCubit);
|
||||
}
|
||||
// 有数据:整页切到「02_设备卡片总览」设计稿 UI。
|
||||
if (state is DeviceListState.DeviceStatusLoaded) {
|
||||
@@ -433,7 +490,8 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
name: (r.alias != null && r.alias!.isNotEmpty) ? r.alias! : r.name,
|
||||
// 型号 · 版本:由 getSiteList 的 productModel 解析(如 MC700 · PRO 旗舰版)
|
||||
modelText: r.modelLabelOf(AppLocalizations.of(context)),
|
||||
snKey: r.id,
|
||||
// SN 与设备详情一致,取 deviceName,不使用数字设备主键。
|
||||
snKey: r.name,
|
||||
status: _robotV2Status(r),
|
||||
battery: r.isOnline ? r.battery.round() : null,
|
||||
robot: r,
|
||||
@@ -527,6 +585,7 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
const DeviceListEvent.DeviceStatusRefresh(),
|
||||
);
|
||||
setState(() => _refreshTick++);
|
||||
unawaited(_realtimeSubscriptions.ensureSubscriptions(_currentSiteId, refresh: true));
|
||||
},
|
||||
child: CustomScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
@@ -564,9 +623,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
padding: const EdgeInsets.all(40),
|
||||
child: Center(
|
||||
child: Text(
|
||||
AppLocalizations.of(context).translate(
|
||||
'device_list_v2.no_matching_device',
|
||||
),
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('device_list_v2.no_matching_device'),
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
color: _v2Gray,
|
||||
@@ -707,7 +766,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
final message = state.errorMessage;
|
||||
if (message == null) return;
|
||||
CapsuleToast.show(
|
||||
message.isEmpty ? l10n.translate('device_list_v2.rename_failed') : message,
|
||||
message.isEmpty
|
||||
? l10n.translate('device_list_v2.rename_failed')
|
||||
: message,
|
||||
showCheck: false,
|
||||
);
|
||||
context.read<RenameDeviceCubit>().reset();
|
||||
@@ -806,9 +867,8 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
const Spacer(),
|
||||
Row(
|
||||
children: [
|
||||
// 上架版隐藏消息入口,接入真实通知后恢复。
|
||||
// _buildV2TopIconButton(Icons.notifications_none, onTap: _v2Todo),
|
||||
// const SizedBox(width: 10),
|
||||
SiteAlarmButton(cubit: _alarmsCubit),
|
||||
const SizedBox(width: 10),
|
||||
_buildV2TopIconButton(
|
||||
Icons.add,
|
||||
onTap: () => _showV2AddSheet(context),
|
||||
@@ -1385,7 +1445,12 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
Widget _buildStatCards(int all, int online, int working, int offline) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final stats = [
|
||||
(Icons.smart_toy_rounded, _v2Blue, all, l10n.translate('device_list_v2.stat_total')),
|
||||
(
|
||||
Icons.smart_toy_rounded,
|
||||
_v2Blue,
|
||||
all,
|
||||
l10n.translate('device_list_v2.stat_total'),
|
||||
),
|
||||
(
|
||||
Icons.wifi_rounded,
|
||||
_v2Blue,
|
||||
@@ -1476,9 +1541,7 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
)
|
||||
AppLocalizations.of(context)
|
||||
.translate('device_list_v2.total_devices_count')
|
||||
.replaceAll('%s', '$all'),
|
||||
style: const TextStyle(fontSize: 12, color: _v2Blue),
|
||||
@@ -1679,10 +1742,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
|
||||
Widget _buildOverviewTelemetry(_V2DeviceItem e) {
|
||||
final sn = e.robot?.name.trim();
|
||||
final online = e.status != DeviceV2Status.offline;
|
||||
final battery = e.battery;
|
||||
return OverviewDeviceTelemetry(
|
||||
deviceSn: widget.isActive && online && sn != null && sn.isNotEmpty
|
||||
deviceSn: widget.isActive && sn != null && sn.isNotEmpty
|
||||
? sn
|
||||
: null,
|
||||
batteryFallback: e.robot != null
|
||||
@@ -2982,12 +3044,9 @@ class _DeviceStatusViewV2State extends State<DeviceStatusViewV2> {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('device_list_v2.device_type_not_supported').replaceAll(
|
||||
'%s',
|
||||
deviceType,
|
||||
),
|
||||
AppLocalizations.of(context)
|
||||
.translate('device_list_v2.device_type_not_supported')
|
||||
.replaceAll('%s', deviceType),
|
||||
),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../../device_alarms/presentation/cubit/device_alarms_cubit.dart';
|
||||
import '../../../../device_alarms/presentation/widgets/site_alarm_button.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
// import 'package:maibu_satabot_v2/components/app_logo.dart';
|
||||
@@ -27,7 +29,8 @@ import 'qr_scanner_page_v2.dart';
|
||||
/// - 背景用设计稿地图背景切图 shebei_bg.png,车图为透明底 shebei-logo.png,
|
||||
/// 车与背景分层不粘连。
|
||||
class NoDevicePageV2 extends StatelessWidget {
|
||||
const NoDevicePageV2({super.key});
|
||||
const NoDevicePageV2({super.key, this.alarmsCubit});
|
||||
final DeviceAlarmsCubit? alarmsCubit;
|
||||
|
||||
// ===== 固定视觉配色(与登录页/我的页 V2 同系) =====
|
||||
static const _bgTop = Color(0xFFFAFCFF);
|
||||
@@ -150,12 +153,10 @@ class NoDevicePageV2 extends StatelessWidget {
|
||||
const Spacer(),
|
||||
Row(
|
||||
children: [
|
||||
// 上架版隐藏消息入口,接入真实通知后恢复。
|
||||
// _buildTopIconButton(
|
||||
// Icons.notifications_none,
|
||||
// onTap: () => _todoTap(context),
|
||||
// ),
|
||||
// const SizedBox(width: 10),
|
||||
if (alarmsCubit case final cubit?) ...[
|
||||
SiteAlarmButton(cubit: cubit),
|
||||
const SizedBox(width: 10),
|
||||
],
|
||||
_buildTopIconButton(
|
||||
Icons.add,
|
||||
onTap: () => _showAddSheet(context),
|
||||
@@ -192,11 +193,7 @@ class NoDevicePageV2 extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
size: 22,
|
||||
color: primary ? Colors.white : _navy,
|
||||
),
|
||||
child: Icon(icon, size: 22, color: primary ? Colors.white : _navy),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -451,11 +448,7 @@ class NoDevicePageV2 extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.close,
|
||||
size: 20,
|
||||
color: _grayText,
|
||||
),
|
||||
icon: const Icon(Icons.close, size: 20, color: _grayText),
|
||||
onPressed: () => Navigator.pop(sheetCtx),
|
||||
),
|
||||
],
|
||||
@@ -545,10 +538,7 @@ class NoDevicePageV2 extends StatelessWidget {
|
||||
children: [
|
||||
Icon(icon, size: 20, color: _navy),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 15, color: _navy),
|
||||
),
|
||||
Text(label, style: const TextStyle(fontSize: 15, color: _navy)),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -599,11 +589,7 @@ class NoDevicePageV2 extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 20,
|
||||
color: Color(0xFFC9CDD4),
|
||||
),
|
||||
const Icon(Icons.chevron_right, size: 20, color: Color(0xFFC9CDD4)),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -10,6 +10,8 @@ import 'package:latlong2/latlong.dart';
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/work_trace_diagnostics.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
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/devices/domain/entities/running_status_entity.dart';
|
||||
@@ -24,6 +26,7 @@ import '../widgets/autonomous/work_record_panels.dart';
|
||||
import '../widgets/autonomous/work_route_panels.dart';
|
||||
import '../widgets/autonomous/work_setting_panel.dart';
|
||||
import '../widgets/autonomous/work_ui.dart';
|
||||
import '../widgets/autonomous/work_task_status_card.dart';
|
||||
import '../widgets/find_robot_sheet.dart';
|
||||
import '../widgets/voice_broadcast_sheet.dart';
|
||||
import 'robot_control_page.dart';
|
||||
@@ -106,6 +109,7 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
int _routeLoadGeneration = 0;
|
||||
|
||||
bool _infoExpanded = true;
|
||||
bool _taskInfoExpanded = false;
|
||||
|
||||
String get _deviceId => widget.robot.name;
|
||||
bool get _isOnline => widget.robot.isOnline;
|
||||
@@ -1165,6 +1169,8 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
],
|
||||
SizedBox(width: m.topGap),
|
||||
_statusDetailButton(m),
|
||||
SizedBox(width: m.topTight ? 6 : m.topGap),
|
||||
_statusDetailButton(m, taskStatus: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1379,27 +1385,40 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _statusDetailButton(_WorkLayout m) {
|
||||
Widget _statusDetailButton(_WorkLayout m, {bool taskStatus = false}) {
|
||||
final k = m.topK;
|
||||
final selected = taskStatus ? _taskInfoExpanded : _infoExpanded;
|
||||
return InkWell(
|
||||
onTap: () => setState(() => _infoExpanded = !_infoExpanded),
|
||||
onTap: () => setState(() {
|
||||
if (taskStatus) {
|
||||
_taskInfoExpanded = !_taskInfoExpanded;
|
||||
_infoExpanded = false;
|
||||
} else {
|
||||
_infoExpanded = !_infoExpanded;
|
||||
_taskInfoExpanded = false;
|
||||
}
|
||||
}),
|
||||
borderRadius: BorderRadius.circular((13 * k).clamp(10.0, 13.0)),
|
||||
child: Container(
|
||||
height: (38 * k).clamp(26.0, 38.0),
|
||||
padding: EdgeInsets.symmetric(horizontal: (16 * k).clamp(10.0, 16.0)),
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
color: selected ? kWtSoftBlue : Colors.white,
|
||||
borderRadius: BorderRadius.circular((13 * k).clamp(10.0, 13.0)),
|
||||
border: Border.all(color: kWtBorder),
|
||||
border: Border.all(color: selected ? kWtBlue : kWtBorder),
|
||||
),
|
||||
child: Text(
|
||||
_l10n.translate('autonomous_work.status_details'),
|
||||
_l10n.translate(
|
||||
taskStatus
|
||||
? 'autonomous_work.task_status.title'
|
||||
: 'autonomous_work.status_details',
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: (13.5 * k).clamp(10.0, 13.5),
|
||||
height: 1.1,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: kWtNavy,
|
||||
color: selected ? kWtBlue : kWtNavy,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -1503,25 +1522,23 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
|
||||
// ===== 左列:机器人信息(头部/头像/底按钮固定,数据行区限高整行滚动)=====
|
||||
Widget _buildLeftColumn(_WorkLayout m) {
|
||||
final showTaskCard = _phase.hasTask && m.cardMaxH >= 430;
|
||||
return Positioned(
|
||||
left: m.margin,
|
||||
top: m.contentTop,
|
||||
width: m.cardW,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: m.cardMaxH),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildRobotInfoCard(m),
|
||||
if (showTaskCard) ...[
|
||||
const SizedBox(height: 8),
|
||||
_buildCurrentTaskCard(m),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
child: _taskInfoExpanded
|
||||
? WorkTaskStatusCard(
|
||||
subscriptions: sl<SiteDeviceRealtimeSubscriptions>(),
|
||||
siteId: sl<SiteCubit>().state.selectedSite?.id,
|
||||
deviceSn: _deviceId,
|
||||
expectedTaskId: _session?.taskId,
|
||||
compact: m.compact,
|
||||
maxHeight: m.cardMaxH,
|
||||
onCollapse: () => setState(() => _taskInfoExpanded = false),
|
||||
)
|
||||
: SingleChildScrollView(child: _buildRobotInfoCard(m)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1844,88 +1861,6 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCurrentTaskCard(_WorkLayout m) {
|
||||
final task = _session;
|
||||
final progress = task?.progress; // null = 该环境不提供进度
|
||||
final subTitle = switch (_phase) {
|
||||
WorkRunState.running => _l10n.translate('autonomous_work.task_running'),
|
||||
WorkRunState.paused => _l10n.translate('autonomous_work.task_paused'),
|
||||
WorkRunState.failed => _l10n.translate(
|
||||
'autonomous_work.task_interrupted',
|
||||
),
|
||||
WorkRunState.queued => _l10n.translate('autonomous_work.task_queued'),
|
||||
WorkRunState.idle => _l10n.translate('autonomous_work.task_not_started'),
|
||||
WorkRunState.finished => _l10n.translate('autonomous_work.task_ended'),
|
||||
};
|
||||
return Container(
|
||||
padding: EdgeInsets.all(m.compact ? 10 : 14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Color(0x1A1A2B4A),
|
||||
blurRadius: 18,
|
||||
offset: Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
subTitle,
|
||||
style: TextStyle(fontSize: m.fsx(11.5, 8.5), color: kWtGray),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
progress == null ? '—' : '${(progress * 100).round()}%',
|
||||
style: TextStyle(
|
||||
fontSize: m.fsx(24, 16),
|
||||
fontWeight: FontWeight.w800,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
child: LinearProgressIndicator(
|
||||
value: progress,
|
||||
minHeight: 6,
|
||||
backgroundColor: kWtSegBg,
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(kWtGreen),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_kvRow(
|
||||
m,
|
||||
_l10n.translate('pv_control.task_field_no'),
|
||||
task == null ? '—' : '#${task.taskId}',
|
||||
),
|
||||
_kvRow(
|
||||
m,
|
||||
_l10n.translate('pv_control.task_field_status'),
|
||||
task == null || task.rawStatus.isEmpty
|
||||
? workRunStateLabel(_phase, _l10n)
|
||||
: '${workRunStateLabel(_phase, _l10n)} · ${task.rawStatus}',
|
||||
),
|
||||
_kvRow(m, _l10n.translate('work_v2.all_work.route'), _routeName),
|
||||
if (task?.routeId != null)
|
||||
_kvRow(
|
||||
m,
|
||||
_l10n.translate('pv_control.task_field_route'),
|
||||
task!.routeId!,
|
||||
),
|
||||
_kvRow(
|
||||
m,
|
||||
_l10n.translate('autonomous_work.dispatched_at'),
|
||||
task?.createdAt ?? '—',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ===== 右侧功能栏(按可用高度均分,保证 6 项完整可见)=====
|
||||
Widget _buildRightRail(_WorkLayout m) {
|
||||
final compact = m.compact;
|
||||
@@ -2299,7 +2234,10 @@ class _RobotAutonomousWorkPageV2State extends State<RobotAutonomousWorkPageV2> {
|
||||
null,
|
||||
2,
|
||||
() {
|
||||
setState(() => _infoExpanded = true);
|
||||
setState(() {
|
||||
_infoExpanded = true;
|
||||
_taskInfoExpanded = false;
|
||||
});
|
||||
CapsuleToast.show(
|
||||
_l10n.translate('autonomous_work.robot_status_opened'),
|
||||
showCheck: false,
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/mower_task_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/autonomous_work/data/site_device_realtime_subscriptions.dart';
|
||||
|
||||
import 'work_ui.dart';
|
||||
|
||||
/// 仅展示设备上报,不参与任务控制和任务生命周期状态的判定。
|
||||
class WorkTaskStatusCard extends StatefulWidget {
|
||||
const WorkTaskStatusCard({
|
||||
super.key,
|
||||
required this.subscriptions,
|
||||
required this.siteId,
|
||||
required this.deviceSn,
|
||||
required this.maxHeight,
|
||||
required this.onCollapse,
|
||||
this.expectedTaskId,
|
||||
this.compact = false,
|
||||
});
|
||||
|
||||
final SiteDeviceRealtimeSubscriptions subscriptions;
|
||||
final int? siteId;
|
||||
final String deviceSn;
|
||||
final String? expectedTaskId;
|
||||
final double maxHeight;
|
||||
final VoidCallback onCollapse;
|
||||
final bool compact;
|
||||
|
||||
@override
|
||||
State<WorkTaskStatusCard> createState() => _WorkTaskStatusCardState();
|
||||
}
|
||||
|
||||
class _WorkTaskStatusCardState extends State<WorkTaskStatusCard> {
|
||||
StreamSubscription<MowerTaskStatusEntity?>? _subscription;
|
||||
Timer? _clock;
|
||||
MowerTaskStatusEntity? _report;
|
||||
bool _failed = false;
|
||||
int _generation = 0;
|
||||
|
||||
AppLocalizations get _l10n => AppLocalizations.of(context);
|
||||
String get _unknown => _l10n.translate('common.unknown');
|
||||
String _label(String key) =>
|
||||
_l10n.translate('autonomous_work.task_status.$key');
|
||||
String _text(Object? value) => value?.toString() ?? _unknown;
|
||||
double get _font => widget.compact ? 10 : 12;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_listen();
|
||||
_clock = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (_report != null && mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant WorkTaskStatusCard oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.subscriptions != widget.subscriptions ||
|
||||
oldWidget.siteId != widget.siteId ||
|
||||
oldWidget.deviceSn != widget.deviceSn ||
|
||||
oldWidget.expectedTaskId != widget.expectedTaskId) {
|
||||
_report = null;
|
||||
_failed = false;
|
||||
_listen();
|
||||
}
|
||||
}
|
||||
|
||||
void _listen() {
|
||||
final generation = ++_generation;
|
||||
_subscription?.cancel();
|
||||
_subscription = widget.subscriptions
|
||||
.watchTaskStatus(siteId: widget.siteId, deviceSn: widget.deviceSn)
|
||||
.listen(
|
||||
(report) {
|
||||
if (!mounted || generation != _generation) return;
|
||||
if (report == null) {
|
||||
setState(() {
|
||||
_report = null;
|
||||
_failed = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (widget.expectedTaskId != null &&
|
||||
report.taskId != null &&
|
||||
report.taskId != widget.expectedTaskId) {
|
||||
return;
|
||||
}
|
||||
final previous = _report;
|
||||
if (previous != null &&
|
||||
previous.taskId == report.taskId &&
|
||||
previous.timestamp != null &&
|
||||
report.timestamp != null &&
|
||||
report.timestamp! < previous.timestamp!) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_report = report;
|
||||
_failed = false;
|
||||
});
|
||||
},
|
||||
onError: (Object error) {
|
||||
if (mounted && generation == _generation) {
|
||||
setState(() => _failed = true);
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
if (mounted && generation == _generation) {
|
||||
setState(() => _failed = true);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_generation++;
|
||||
_clock?.cancel();
|
||||
_subscription?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _number(double? value, String unit) =>
|
||||
value == null ? _unknown : '${value.toStringAsFixed(2)} $unit';
|
||||
|
||||
String _duration(double? seconds) {
|
||||
if (seconds == null) return _unknown;
|
||||
final duration = Duration(seconds: seconds.round());
|
||||
String pad(int n) => n.toString().padLeft(2, '0');
|
||||
final minutes = pad(duration.inMinutes.remainder(60));
|
||||
final tail = '$minutes:${pad(duration.inSeconds.remainder(60))}';
|
||||
return duration.inHours > 0 ? '${pad(duration.inHours)}:$tail' : tail;
|
||||
}
|
||||
|
||||
String _status(String? value) => switch (value?.toLowerCase()) {
|
||||
null => _unknown,
|
||||
'running' => _label('running'),
|
||||
'paused' => _label('paused'),
|
||||
'completed' || 'finished' => _label('completed'),
|
||||
'failed' => _label('failed'),
|
||||
'canceled' || 'cancelled' => _label('canceled'),
|
||||
'idle' => _label('idle'),
|
||||
_ => value!,
|
||||
};
|
||||
|
||||
String _timestamp(int? milliseconds) {
|
||||
if (milliseconds == null || milliseconds > 8640000000000000) {
|
||||
return _unknown;
|
||||
}
|
||||
final time = DateTime.fromMillisecondsSinceEpoch(milliseconds).toLocal();
|
||||
String pad(int n) => n.toString().padLeft(2, '0');
|
||||
return '${time.year}-${pad(time.month)}-${pad(time.day)} '
|
||||
'${pad(time.hour)}:${pad(time.minute)}:${pad(time.second)}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final report = _report;
|
||||
final age = report == null
|
||||
? null
|
||||
: DateTime.now()
|
||||
.difference(report.receivedAt)
|
||||
.inSeconds
|
||||
.clamp(0, 999999);
|
||||
final stale = age != null && age >= 15;
|
||||
final warning = _failed || stale;
|
||||
final progress = report?.progress;
|
||||
final mode = report?.mode == 'coverage'
|
||||
? _label('coverage')
|
||||
: _text(report?.mode);
|
||||
final phaseName = report?.phaseName == 'COVERING'
|
||||
? _label('covering')
|
||||
: _text(report?.phaseName);
|
||||
|
||||
return Container(
|
||||
constraints: BoxConstraints(maxHeight: widget.maxHeight),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Color(0x1A1A2B4A),
|
||||
blurRadius: 18,
|
||||
offset: Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 4, 4, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.assignment_outlined, size: 16, color: kWtBlue),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_label('title'),
|
||||
style: TextStyle(
|
||||
fontSize: _font + 2,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: _label('collapse'),
|
||||
onPressed: widget.onCollapse,
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(
|
||||
Icons.keyboard_arrow_up_rounded,
|
||||
color: kWtBlue,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
_failed
|
||||
? _label('unavailable')
|
||||
: report == null
|
||||
? _label('waiting')
|
||||
: stale
|
||||
? _label('stale')
|
||||
: _l10n.translate(
|
||||
'autonomous_work.task_status.updated',
|
||||
{'seconds': age},
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: _font,
|
||||
color: warning ? kWtWarn : kWtGray,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_row(_label('task_id'), _text(report?.taskId)),
|
||||
_row(_label('status'), _status(report?.status)),
|
||||
_row(_label('mode'), mode),
|
||||
_row(_label('phase_name'), phaseName),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_label('progress'),
|
||||
style: TextStyle(fontSize: _font, color: kWtGray),
|
||||
),
|
||||
Text(
|
||||
progress == null
|
||||
? _unknown
|
||||
: '${(progress * 100).toStringAsFixed(2)}%',
|
||||
style: TextStyle(
|
||||
fontSize: _font + 12,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: LinearProgressIndicator(
|
||||
value: progress ?? 0,
|
||||
minHeight: 5,
|
||||
backgroundColor: kWtSegBg,
|
||||
color: progress == null || warning ? kWtGray : kWtGreen,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_pair(
|
||||
(_label('elapsed_s'), _duration(report?.elapsedSeconds)),
|
||||
(_label('eta_s'), _duration(report?.etaSeconds)),
|
||||
),
|
||||
_pair(
|
||||
(
|
||||
_label('distance_traveled'),
|
||||
_number(report?.distanceTraveled, 'm'),
|
||||
),
|
||||
(
|
||||
_label('distance_remaining'),
|
||||
_number(report?.distanceRemaining, 'm'),
|
||||
),
|
||||
),
|
||||
_pair(
|
||||
(_label('speed'), _number(report?.speed, 'm/s')),
|
||||
(
|
||||
_label('number_of_recoveries'),
|
||||
_text(report?.numberOfRecoveries),
|
||||
),
|
||||
),
|
||||
_pair(
|
||||
// 面向用户的分区序号从 1 开始,原始索引在报文详情里保留。
|
||||
(
|
||||
_label('current_cell'),
|
||||
_text(
|
||||
report?.currentCellIndex == null
|
||||
? null
|
||||
: report!.currentCellIndex! + 1,
|
||||
),
|
||||
),
|
||||
(_label('total_cells'), _text(report?.totalCells)),
|
||||
),
|
||||
Theme(
|
||||
data: Theme.of(
|
||||
context,
|
||||
).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
childrenPadding: EdgeInsets.zero,
|
||||
dense: true,
|
||||
title: Text(
|
||||
_label('details'),
|
||||
style: TextStyle(fontSize: _font, color: kWtBlue),
|
||||
),
|
||||
children: [
|
||||
_row(
|
||||
_label('protocol_version'),
|
||||
_text(report?.protocolVersion),
|
||||
),
|
||||
_row(_label('message_id'), _text(report?.messageId)),
|
||||
_row(_label('sn'), _text(report?.sn)),
|
||||
_row(_label('command_id'), _text(report?.commandId)),
|
||||
_row(
|
||||
_label('timestamp'),
|
||||
_timestamp(report?.timestamp),
|
||||
),
|
||||
_row('timestamp', _text(report?.timestamp)),
|
||||
_row('phase', _text(report?.phase)),
|
||||
_row('task_phase', _text(report?.taskPhase)),
|
||||
_row(
|
||||
'current_cell_index',
|
||||
_text(report?.currentCellIndex),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: SelectableText(
|
||||
report == null
|
||||
? _unknown
|
||||
: const JsonEncoder.withIndent(
|
||||
' ',
|
||||
).convert(report.raw),
|
||||
style: TextStyle(fontSize: _font, color: kWtGray),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(String label, String value) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(fontSize: _font, color: kWtGray),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
value,
|
||||
textAlign: TextAlign.right,
|
||||
style: TextStyle(
|
||||
fontSize: _font,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _pair((String, String) left, (String, String) right) {
|
||||
Widget metric((String, String) item) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.$1,
|
||||
style: TextStyle(fontSize: _font, color: kWtGray),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
item.$2,
|
||||
style: TextStyle(
|
||||
fontSize: _font + 2,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: kWtNavy,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: metric(left)),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: metric(right)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ class AlarmModel {
|
||||
required this.level,
|
||||
required this.status,
|
||||
this.aiDiagnosis,
|
||||
this.deviceId = '',
|
||||
this.siteId,
|
||||
});
|
||||
|
||||
final String id;
|
||||
@@ -23,6 +25,8 @@ class AlarmModel {
|
||||
final AlarmLevel level;
|
||||
final AlarmStatus status;
|
||||
final String? aiDiagnosis;
|
||||
final String deviceId;
|
||||
final int? siteId;
|
||||
|
||||
/// 从 JSON 创建
|
||||
factory AlarmModel.fromJson(Map<String, dynamic> json) {
|
||||
@@ -36,6 +40,8 @@ class AlarmModel {
|
||||
level: _parseLevel(json['alarmLevel']?.toString() ?? ''),
|
||||
status: _parseStatus(json['handleStatus']),
|
||||
aiDiagnosis: json['aiDiagnosis']?.toString(),
|
||||
deviceId: json['deviceId']?.toString() ?? '',
|
||||
siteId: int.tryParse('${json['siteId']}'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -50,6 +56,8 @@ class AlarmModel {
|
||||
'level': level.name,
|
||||
'status': status.name,
|
||||
'aiDiagnosis': aiDiagnosis,
|
||||
'deviceId': deviceId,
|
||||
'siteId': siteId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,6 +72,8 @@ class AlarmModel {
|
||||
level: level,
|
||||
status: status,
|
||||
aiDiagnosis: aiDiagnosis,
|
||||
deviceId: deviceId,
|
||||
siteId: siteId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -78,6 +88,8 @@ class AlarmModel {
|
||||
level: entity.level,
|
||||
status: entity.status,
|
||||
aiDiagnosis: entity.aiDiagnosis,
|
||||
deviceId: entity.deviceId,
|
||||
siteId: entity.siteId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -85,12 +97,16 @@ class AlarmModel {
|
||||
final lowerLevel = level.toLowerCase();
|
||||
switch (lowerLevel) {
|
||||
case 'danger':
|
||||
case '1':
|
||||
return AlarmLevel.danger;
|
||||
case 'warning':
|
||||
case '2':
|
||||
return AlarmLevel.warning;
|
||||
case 'low':
|
||||
case '3':
|
||||
return AlarmLevel.low;
|
||||
case 'info':
|
||||
case '4':
|
||||
return AlarmLevel.info;
|
||||
default:
|
||||
return AlarmLevel.warning;
|
||||
@@ -98,6 +114,10 @@ class AlarmModel {
|
||||
}
|
||||
|
||||
static AlarmStatus _parseStatus(dynamic status) {
|
||||
if (status is String) {
|
||||
final code = int.tryParse(status);
|
||||
if (code != null) return _parseStatus(code);
|
||||
}
|
||||
if (status is int) {
|
||||
switch (status) {
|
||||
case 1:
|
||||
|
||||
@@ -12,6 +12,8 @@ class AlarmEntity extends Equatable {
|
||||
required this.level,
|
||||
required this.status,
|
||||
this.aiDiagnosis,
|
||||
this.deviceId = '',
|
||||
this.siteId,
|
||||
});
|
||||
|
||||
/// 告警 ID
|
||||
@@ -37,16 +39,33 @@ class AlarmEntity extends Equatable {
|
||||
|
||||
/// AI 诊断建议(可选)
|
||||
final String? aiDiagnosis;
|
||||
final String deviceId;
|
||||
final int? siteId;
|
||||
|
||||
AlarmEntity copyWith({AlarmStatus? status}) => AlarmEntity(
|
||||
id: id,
|
||||
title: title,
|
||||
area: area,
|
||||
device: device,
|
||||
time: time,
|
||||
level: level,
|
||||
status: status ?? this.status,
|
||||
aiDiagnosis: aiDiagnosis,
|
||||
deviceId: deviceId,
|
||||
siteId: siteId,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
title,
|
||||
area,
|
||||
device,
|
||||
time,
|
||||
level,
|
||||
status,
|
||||
aiDiagnosis,
|
||||
];
|
||||
id,
|
||||
title,
|
||||
area,
|
||||
device,
|
||||
time,
|
||||
level,
|
||||
status,
|
||||
aiDiagnosis,
|
||||
deviceId,
|
||||
siteId,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@ import 'package:maibu_satabot_v2/features/v2/waring_center/presentation/widgets/
|
||||
/// 告警详情页面
|
||||
class AlarmDetailPage extends StatefulWidget {
|
||||
final String alarmId;
|
||||
final Widget Function(BuildContext, AlarmDetailEntity)? actionBuilder;
|
||||
|
||||
const AlarmDetailPage({super.key, required this.alarmId});
|
||||
const AlarmDetailPage({super.key, required this.alarmId, this.actionBuilder});
|
||||
|
||||
@override
|
||||
State<AlarmDetailPage> createState() => _AlarmDetailPageState();
|
||||
@@ -33,9 +34,7 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: isDark
|
||||
? SystemUiOverlayStyle.light
|
||||
: SystemUiOverlayStyle.dark,
|
||||
value: isDark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark,
|
||||
child: Scaffold(
|
||||
backgroundColor: context.appColors.pageBackground,
|
||||
appBar: _buildAppBar(),
|
||||
@@ -95,7 +94,7 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: Icon(Icons.arrow_back, color: context.appColors.textPrimary),
|
||||
onPressed: () => context.pop(),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
title: Text(
|
||||
'告警详情',
|
||||
@@ -251,7 +250,9 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: _buildBottomButtons(state),
|
||||
child:
|
||||
widget.actionBuilder?.call(context, alarm) ??
|
||||
_buildBottomButtons(state),
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -265,7 +266,11 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
color: context.appColors.cardBackground,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(color: context.appColors.cardShadow, blurRadius: 4, offset: const Offset(0, 2)),
|
||||
BoxShadow(
|
||||
color: context.appColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
@@ -390,7 +395,11 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
color: context.appColors.cardBackground,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(color: context.appColors.cardShadow, blurRadius: 4, offset: const Offset(0, 2)),
|
||||
BoxShadow(
|
||||
color: context.appColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
@@ -474,7 +483,11 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
}
|
||||
|
||||
Widget _buildDivider() {
|
||||
return Divider(height: 24, thickness: 0.5, color: context.appColors.divider);
|
||||
return Divider(
|
||||
height: 24,
|
||||
thickness: 0.5,
|
||||
color: context.appColors.divider,
|
||||
);
|
||||
}
|
||||
|
||||
bool _hasHistoryData(HistoryMetrics historyData) {
|
||||
@@ -491,7 +504,11 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
color: context.appColors.cardBackground,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(color: context.appColors.cardShadow, blurRadius: 4, offset: const Offset(0, 2)),
|
||||
BoxShadow(
|
||||
color: context.appColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
@@ -646,7 +663,9 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
child: ElevatedButton(
|
||||
onPressed: isLoading || isDisabled ? null : onPressed,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isPrimary ? context.appColors.primary : context.appColors.cardBackground,
|
||||
backgroundColor: isPrimary
|
||||
? context.appColors.primary
|
||||
: context.appColors.cardBackground,
|
||||
foregroundColor: isPrimary ? Colors.white : context.appColors.primary,
|
||||
elevation: 0,
|
||||
side: isPrimary ? null : BorderSide(color: context.appColors.primary),
|
||||
@@ -681,18 +700,29 @@ class _AlarmDetailPageState extends State<AlarmDetailPage> {
|
||||
backgroundColor: context.appColors.cardBackground,
|
||||
title: Text(
|
||||
'AI诊断结果',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: context.appColors.textPrimary),
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: context.appColors.textPrimary,
|
||||
),
|
||||
),
|
||||
content: SingleChildScrollView(
|
||||
child: Text(
|
||||
result,
|
||||
style: TextStyle(fontSize: 14, height: 1.6, color: context.appColors.textSecondary),
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
height: 1.6,
|
||||
color: context.appColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => context.pop(),
|
||||
child: Text('关闭', style: TextStyle(color: context.appColors.primary)),
|
||||
child: Text(
|
||||
'关闭',
|
||||
style: TextStyle(color: context.appColors.primary),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -6,26 +6,40 @@ import 'package:maibu_satabot_v2/features/v2/waring_center/presentation/constant
|
||||
|
||||
/// 告警项卡片
|
||||
class AlarmItemCard extends StatelessWidget {
|
||||
const AlarmItemCard({super.key, required this.alarm, this.onTap});
|
||||
const AlarmItemCard({
|
||||
super.key,
|
||||
required this.alarm,
|
||||
this.onTap,
|
||||
this.trailing,
|
||||
this.margin,
|
||||
});
|
||||
|
||||
final AlarmEntity alarm;
|
||||
final VoidCallback? onTap;
|
||||
final Widget? trailing;
|
||||
final EdgeInsetsGeometry? margin;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(
|
||||
horizontal: AlarmDimensions.horizontalPadding,
|
||||
vertical: 6,
|
||||
),
|
||||
margin:
|
||||
margin ??
|
||||
const EdgeInsets.symmetric(
|
||||
horizontal: AlarmDimensions.horizontalPadding,
|
||||
vertical: 6,
|
||||
),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: context.appColors.cardBackground,
|
||||
borderRadius: BorderRadius.circular(AlarmDimensions.borderRadius),
|
||||
boxShadow: [
|
||||
BoxShadow(color: context.appColors.cardShadow, blurRadius: 4, offset: const Offset(0, 2)),
|
||||
BoxShadow(
|
||||
color: context.appColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
@@ -79,14 +93,18 @@ class AlarmItemCard extends StatelessWidget {
|
||||
// 第三行:时间和状态
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
alarm.time,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: context.appColors.textTertiary,
|
||||
Expanded(
|
||||
child: Text(
|
||||
alarm.time,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: context.appColors.textTertiary,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
alarm.status.label,
|
||||
style: TextStyle(
|
||||
@@ -96,6 +114,7 @@ class AlarmItemCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
if (trailing != null) trailing!,
|
||||
Icon(
|
||||
Icons.arrow_forward_ios,
|
||||
size: 12,
|
||||
|
||||
Reference in New Issue
Block a user