接入设备故障告警和场站实时任务进度
This commit is contained in:
@@ -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(''));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user