接入设备故障告警和场站实时任务进度
This commit is contained in:
@@ -9,6 +9,7 @@ import '../../domain/entities/mower_location_entity.dart';
|
||||
import '../../domain/entities/real_time_message_entity.dart';
|
||||
import '../../domain/entities/route_status_entity.dart';
|
||||
import '../../domain/entities/host_realtime_message_entity.dart';
|
||||
import '../../domain/entities/mower_task_status_entity.dart';
|
||||
|
||||
/// 割草机实时状态 MQTT 数据源(替代原 TCP 0x02 机器状态推送)
|
||||
///
|
||||
@@ -24,6 +25,8 @@ abstract class MowerRealtimeDataSource {
|
||||
/// 🔥 主机实时状态(device/{sn}/host/realTime/message,新增话题,纯附加)
|
||||
Stream<HostRealtimeMessageEntity> get hostRealtimeStream;
|
||||
|
||||
Stream<MowerTaskStatusEntity> watchTaskStatus(String deviceSn);
|
||||
|
||||
/// 按设备观察概览所需的电量和控制模式,订阅随监听者释放。
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
@@ -81,6 +84,61 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
String _routeTopic(String sn) => 'device/$sn/$_routeSuffix';
|
||||
String _hostRealtimeTopic(String sn) => 'device/$sn/$_hostRealtimeSuffix';
|
||||
|
||||
@override
|
||||
Stream<MowerTaskStatusEntity> watchTaskStatus(String deviceSn) {
|
||||
final sn = deviceSn.trim();
|
||||
final messages = mqttClient.messageStream;
|
||||
if (sn.isEmpty || messages == null) return const Stream.empty();
|
||||
|
||||
final topic = 'mower/$sn/task/status/post';
|
||||
StreamSubscription<MqttMessage>? messageSubscription;
|
||||
Future<void>? topicSubscription;
|
||||
late final StreamController<MowerTaskStatusEntity> controller;
|
||||
controller = StreamController<MowerTaskStatusEntity>(
|
||||
onListen: () {
|
||||
// 先接收再订阅,避免漏掉订阅后立即到达的首帧。
|
||||
messageSubscription = messages
|
||||
.where((msg) => msg.topic == topic)
|
||||
.listen(
|
||||
(message) {
|
||||
try {
|
||||
final json = jsonDecode(message.payload);
|
||||
if (json is! Map<String, dynamic>) return;
|
||||
final status = MowerTaskStatusEntity.fromJson(
|
||||
json,
|
||||
receivedAt: message.timestamp,
|
||||
);
|
||||
if (status.sn != null && status.sn != sn) return;
|
||||
controller.add(status);
|
||||
} on FormatException catch (error) {
|
||||
debugPrint('[任务状态] 报文解析失败 $topic: $error');
|
||||
}
|
||||
},
|
||||
onError: controller.addError,
|
||||
onDone: controller.close,
|
||||
);
|
||||
topicSubscription = mqttClient.subscribe(topic).catchError((
|
||||
Object error,
|
||||
StackTrace stackTrace,
|
||||
) {
|
||||
if (!controller.isClosed) controller.addError(error, stackTrace);
|
||||
});
|
||||
},
|
||||
onCancel: () async {
|
||||
await messageSubscription?.cancel();
|
||||
final subscription = topicSubscription;
|
||||
if (subscription == null) return;
|
||||
await subscription;
|
||||
try {
|
||||
await mqttClient.unsubscribe(topic);
|
||||
} catch (error) {
|
||||
debugPrint('[任务状态] 释放订阅失败 $topic: $error');
|
||||
}
|
||||
},
|
||||
);
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
|
||||
@@ -136,6 +136,9 @@ class MqttClientImpl implements MqttClient {
|
||||
client.onSubscribed = (topic) {
|
||||
if (identical(_client, client)) _onSubscribed(topic);
|
||||
};
|
||||
client.onSubscribeFail = (topic) {
|
||||
if (identical(_client, client)) _onSubscribeFail(topic);
|
||||
};
|
||||
|
||||
var connMessage = mqtt.MqttConnectMessage()
|
||||
.withClientIdentifier(client.clientIdentifier)
|
||||
@@ -170,25 +173,46 @@ class MqttClientImpl implements MqttClient {
|
||||
Future<void> subscribe(String topic) async {
|
||||
final previousRefs = _subscriptionRefs[topic] ?? 0;
|
||||
_subscriptionRefs[topic] = previousRefs + 1;
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'SUB_REQUEST topic=$topic connected=$_isConnected '
|
||||
'broker=${_currentConfig?.host}:${_currentConfig?.port} refs=${previousRefs + 1}',
|
||||
);
|
||||
}
|
||||
|
||||
if (!_isConnected || _client == null) {
|
||||
debugPrint('[MqttClient] queued subscription while disconnected: $topic');
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'SUB_QUEUED topic=$topic configReady=${_currentConfig != null} '
|
||||
'connecting=$_isConnecting manualDisconnect=$_manualDisconnect',
|
||||
);
|
||||
}
|
||||
_scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousRefs > 0) {
|
||||
debugPrint('[MqttClient] subscription already active: $topic');
|
||||
if (_isAlarmTopic(topic))
|
||||
_logAlarm('SUB_REUSED topic=$topic refs=${previousRefs + 1}');
|
||||
return;
|
||||
}
|
||||
|
||||
debugPrint('${LogTime.now()} 📮 [$clientName] 发起订阅: $topic');
|
||||
_client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
|
||||
final subscription = _client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'SUB_SENT topic=$topic acceptedLocally=${subscription != null} 等待SUB_ACK',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {
|
||||
final currentRefs = _subscriptionRefs[topic] ?? 0;
|
||||
if (_isAlarmTopic(topic))
|
||||
_logAlarm('UNSUB_REQUEST topic=$topic refs=$currentRefs');
|
||||
if (currentRefs <= 1) {
|
||||
_subscriptionRefs.remove(topic);
|
||||
} else {
|
||||
@@ -229,7 +253,13 @@ class MqttClientImpl implements MqttClient {
|
||||
(msg.payload as mqtt.MqttPublishMessage).payload.message,
|
||||
);
|
||||
|
||||
debugPrint('${LogTime.now()} 📥 [$clientName] 收到消息 [$topic]: $payload');
|
||||
// debugPrint('${LogTime.now()} 📥 [$clientName] 收到消息 [$topic]: $payload');
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'RX_RAW topic=$topic hasListener=${_messageController.hasListener}',
|
||||
);
|
||||
_logAlarm('RX_PAYLOAD $payload');
|
||||
}
|
||||
_messageController.add(MqttMessage(topic: topic, payload: payload));
|
||||
}
|
||||
},
|
||||
@@ -248,6 +278,11 @@ class MqttClientImpl implements MqttClient {
|
||||
|
||||
for (final topic in _subscriptionRefs.keys) {
|
||||
debugPrint('${LogTime.now()} 📮 [$clientName] 重连后重新订阅: $topic');
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'RESUB_SENT topic=$topic broker=${_currentConfig?.host}:${_currentConfig?.port}',
|
||||
);
|
||||
}
|
||||
_client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
|
||||
}
|
||||
}
|
||||
@@ -260,6 +295,8 @@ class MqttClientImpl implements MqttClient {
|
||||
void _onDisconnected() {
|
||||
debugPrint('${LogTime.now()} ⚠️ [$clientName] 连接断开');
|
||||
_isConnected = false;
|
||||
final alarmTopics = _subscriptionRefs.keys.where(_isAlarmTopic).join(',');
|
||||
if (alarmTopics.isNotEmpty) _logAlarm('DISCONNECTED topics=$alarmTopics');
|
||||
if (!_manualDisconnect) {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
@@ -267,8 +304,25 @@ class MqttClientImpl implements MqttClient {
|
||||
|
||||
void _onSubscribed(String topic) {
|
||||
debugPrint('${LogTime.now()} ✅ [$clientName] 订阅确认成功: $topic');
|
||||
if (_isAlarmTopic(topic)) {
|
||||
_logAlarm(
|
||||
'SUB_ACK topic=$topic broker=${_currentConfig?.host}:${_currentConfig?.port}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _onSubscribeFail(String topic) {
|
||||
if (_isAlarmTopic(topic)) _logAlarm('SUB_REJECTED topic=$topic');
|
||||
}
|
||||
|
||||
bool _isAlarmTopic(String topic) =>
|
||||
topic.startsWith('device/') && topic.endsWith('/error/post');
|
||||
|
||||
void _logAlarm(String message) => debugPrintSynchronously(
|
||||
'${LogTime.now()} [设备告警][MQTT][$clientName] $message',
|
||||
wrapWidth: 800,
|
||||
);
|
||||
|
||||
void _scheduleReconnect() {
|
||||
final config = _currentConfig;
|
||||
if (_manualDisconnect || config == null || _isConnected || _isConnecting) {
|
||||
@@ -278,7 +332,9 @@ class MqttClientImpl implements MqttClient {
|
||||
if (_reconnectTimer?.isActive ?? false) return;
|
||||
|
||||
final delay = Duration(milliseconds: config.reconnectDelayMs);
|
||||
debugPrint('${LogTime.now()} ⏳ [$clientName] ${delay.inMilliseconds}ms 后尝试重连');
|
||||
debugPrint(
|
||||
'${LogTime.now()} ⏳ [$clientName] ${delay.inMilliseconds}ms 后尝试重连',
|
||||
);
|
||||
_reconnectTimer = Timer(delay, () async {
|
||||
if (_manualDisconnect || _isConnected || _isConnecting) return;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import '../../domain/entities/mower_location_entity.dart';
|
||||
import '../../domain/entities/real_time_message_entity.dart';
|
||||
import '../../domain/entities/route_status_entity.dart';
|
||||
import '../../domain/entities/host_realtime_message_entity.dart';
|
||||
import '../../domain/entities/mower_task_status_entity.dart';
|
||||
|
||||
class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
|
||||
final MowerRealtimeDataSource dataSource;
|
||||
@@ -28,6 +29,10 @@ class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
|
||||
Stream<HostRealtimeMessageEntity> get hostRealtimeStream =>
|
||||
dataSource.hostRealtimeStream;
|
||||
|
||||
@override
|
||||
Stream<MowerTaskStatusEntity> watchTaskStatus(String deviceSn) =>
|
||||
dataSource.watchTaskStatus(deviceSn);
|
||||
|
||||
@override
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
|
||||
Reference in New Issue
Block a user