绑定设备+覆盖模式+控制显示bug+在线更新

This commit is contained in:
2026-09-01 08:59:20 +08:00
parent 0fa67a127b
commit 61bce2c1cf
49 changed files with 2424 additions and 720 deletions

View File

@@ -0,0 +1,178 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../../../../logging/log_time.dart';
import '../../domain/interfaces/mqtt_client.dart';
import '../../domain/models/mqtt_message.dart';
import '../../domain/entities/mower_location_entity.dart';
import '../../domain/entities/real_time_message_entity.dart';
import '../../domain/entities/route_status_entity.dart';
/// 割草机实时状态 MQTT 数据源(替代原 TCP 0x02 机器状态推送)
///
/// 订阅主题:
/// - 车辆实时状态 mower/{sn}/property/realtime/post(1Hz,不含定位)
/// - 高频定位 mower/{sn}/property/location/post(5-10Hz)
/// - 路径规划 device/{deviceId}/route/post(任务执行后推送覆盖清扫路线)
abstract class MowerRealtimeDataSource {
Stream<RealTimeMessageEntity> get vehicleStream;
Stream<MowerLocationEntity> get locationStream;
Stream<RouteStatusEntity> get routeStatusStream;
/// 按设备 SN 启动订阅:自动退订旧设备主题、同 SN 去重
Future<void> startListening({required String deviceSn});
Future<void> stopListening();
}
class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
final MqttClient mqttClient;
static const String _realtimeSuffix = 'property/realtime/post';
static const String _locationSuffix = 'property/location/post';
static const String _routeSuffix = 'route/post';
final _vehicleController =
StreamController<RealTimeMessageEntity>.broadcast();
final _locationController = StreamController<MowerLocationEntity>.broadcast();
final _routeController = StreamController<RouteStatusEntity>.broadcast();
StreamSubscription<MqttMessage>? _subscription;
/// 当前监听的设备 SN
String? _deviceSn;
/// 收帧计数(用于标记首帧)
int _vehicleMsgCount = 0;
int _locationMsgCount = 0;
int _routeMsgCount = 0;
MowerRealtimeDataSourceImpl(this.mqttClient);
@override
Stream<RealTimeMessageEntity> get vehicleStream => _vehicleController.stream;
@override
Stream<MowerLocationEntity> get locationStream => _locationController.stream;
@override
Stream<RouteStatusEntity> get routeStatusStream => _routeController.stream;
String _realtimeTopic(String sn) => 'mower/$sn/$_realtimeSuffix';
String _locationTopic(String sn) => 'mower/$sn/$_locationSuffix';
String _routeTopic(String sn) => 'device/$sn/$_routeSuffix';
@override
Future<void> startListening({required String deviceSn}) async {
if (deviceSn.isEmpty) {
debugPrint('${LogTime.now()} ⚠️ [MowerRealtimeDataSource] 订阅跳过:设备SN为空');
return;
}
// 🔥 同一设备重复调用:去重,不重复订阅(参照 DroneOsdDataSource 已验证的模式)
if (_deviceSn == deviceSn && _subscription != null) {
debugPrint('${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn');
return;
}
// 🔥 切换设备:先退订旧设备的主题,防止数据串台
if (_deviceSn != null && _deviceSn!.isNotEmpty) {
await mqttClient.unsubscribe(_realtimeTopic(_deviceSn!));
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn');
}
_deviceSn = deviceSn;
_vehicleMsgCount = 0;
_locationMsgCount = 0;
_routeMsgCount = 0;
await mqttClient.subscribe(_realtimeTopic(deviceSn));
await mqttClient.subscribe(_locationTopic(deviceSn));
await mqttClient.subscribe(_routeTopic(deviceSn));
// 消息流监听只建立一次,按 _deviceSn 过滤
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
debugPrint('${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn');
debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}');
debugPrint(' 定位: ${_locationTopic(deviceSn)}');
debugPrint(' 路径规划: ${_routeTopic(deviceSn)}');
}
@override
Future<void> stopListening() async {
if (_deviceSn == null || _deviceSn!.isEmpty) return;
await mqttClient.unsubscribe(_realtimeTopic(_deviceSn!));
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn');
_deviceSn = null;
}
void _handleMessage(MqttMessage message) {
final sn = _deviceSn;
if (sn == null || sn.isEmpty) return;
// 🔥 防串台:只处理当前监听设备的主题(mower/ 和 device/ 前缀都要匹配)
if (!message.topic.contains('mower/$sn/') &&
!message.topic.contains('device/$sn/')) return;
// 🔥 第一阶段:打印原始报文,确认格式后再完善解析
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] ──────── 收到消息 ────────');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] payload: ${message.payload}');
try {
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
if (message.topic.endsWith(_realtimeSuffix)) {
// {name, value, unit} 数据点格式与 RealTimeMessageEntity 吻合,防御性解析
final vehicle = RealTimeMessageEntity.fromJson(jsonData);
if (vehicle.data.isNotEmpty) {
_vehicleMsgCount++;
if (_vehicleMsgCount == 1) {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 车辆实时首帧到达: $sn');
}
debugPrint('${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个');
for (final dp in vehicle.data) {
debugPrint('${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}');
}
_vehicleController.add(vehicle);
}
} else if (message.topic.endsWith(_locationSuffix)) {
_locationMsgCount++;
if (_locationMsgCount == 1) {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 定位首帧到达: $sn');
}
// 🔥 关键修复:坐标在 data 子对象中,不是顶层
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
final location = MowerLocationEntity.fromJson(dataObj);
debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}');
_locationController.add(location);
} else if (message.topic.endsWith(_routeSuffix)) {
_routeMsgCount++;
if (_routeMsgCount == 1) {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 路径规划首帧到达: $sn');
}
final routeMsg = RouteStatusEntity.fromJson(jsonData);
debugPrint('${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}');
_routeController.add(routeMsg);
}
} catch (e) {
debugPrint('${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败: $e');
}
}
void dispose() {
stopListening();
_subscription?.cancel();
_subscription = null;
_vehicleController.close();
_locationController.close();
_routeController.close();
}
}

View File

@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import 'package:mqtt_client/mqtt_client.dart' as mqtt;
import 'package:mqtt_client/mqtt_server_client.dart' as mqtt_server;
import '../../../../logging/log_time.dart';
import '../../domain/interfaces/mqtt_client.dart';
import '../../domain/models/mqtt_config.dart';
import '../../domain/models/mqtt_message.dart';
@@ -13,6 +14,9 @@ class MqttClientImpl implements MqttClient {
final _messageController = StreamController<MqttMessage>.broadcast();
final Map<String, int> _subscriptionRefs = <String, int>{};
/// 客户端名称,用于日志区分(如 droneOsdClient / taskMessageClient / mowerRealtimeClient)
final String clientName;
MqttConfig? _currentConfig;
StreamSubscription? _updatesSubscription;
Timer? _reconnectTimer;
@@ -20,6 +24,8 @@ class MqttClientImpl implements MqttClient {
bool _isConnecting = false;
bool _manualDisconnect = false;
MqttClientImpl({this.clientName = 'MqttClient'});
@override
Stream<MqttMessage>? get messageStream => _messageController.stream;
@@ -50,13 +56,13 @@ class MqttClientImpl implements MqttClient {
_client = _createClient(config);
_configureClient(_client!, config);
debugPrint('[MqttClient] connecting to ${config.connectionAddress}');
debugPrint('${LogTime.now()} 🔌 [$clientName] 正在连接 ${config.connectionAddress}:${config.port} (clientId=${config.clientId})');
await _client!.connect(config.username, config.password);
if (_client!.connectionStatus?.state ==
mqtt.MqttConnectionState.connected) {
_isConnected = true;
debugPrint('[MqttClient] connected');
debugPrint('${LogTime.now()} ✅ [$clientName] 连接成功 ${config.connectionAddress}:${config.port}');
_listenToMessages();
_resubscribeAll();
} else {
@@ -65,7 +71,7 @@ class MqttClientImpl implements MqttClient {
);
}
} catch (e) {
debugPrint('[MqttClient] connect error: $e');
debugPrint('${LogTime.now()} ❌ [$clientName] 连接失败: $e');
_isConnected = false;
_isConnecting = false;
_scheduleReconnect();
@@ -153,7 +159,7 @@ class MqttClientImpl implements MqttClient {
return;
}
debugPrint('[MqttClient] subscribe: $topic');
debugPrint('${LogTime.now()} 📮 [$clientName] 发起订阅: $topic');
_client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
}
@@ -173,7 +179,7 @@ class MqttClientImpl implements MqttClient {
return;
}
debugPrint('[MqttClient] unsubscribe: $topic');
debugPrint('${LogTime.now()} 🔕 [$clientName] 退订: $topic');
_client!.unsubscribe(topic);
}
@@ -198,7 +204,7 @@ class MqttClientImpl implements MqttClient {
(msg.payload as mqtt.MqttPublishMessage).payload.message,
);
debugPrint('[MqttClient] received [$topic]: $payload');
debugPrint('${LogTime.now()} 📥 [$clientName] 收到消息 [$topic]: $payload');
_messageController.add(MqttMessage(topic: topic, payload: payload));
}
},
@@ -215,7 +221,7 @@ class MqttClientImpl implements MqttClient {
if (_subscriptionRefs.isEmpty || _client == null) return;
for (final topic in _subscriptionRefs.keys) {
debugPrint('[MqttClient] resubscribe: $topic');
debugPrint('${LogTime.now()} 📮 [$clientName] 重连后重新订阅: $topic');
_client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
}
}
@@ -226,7 +232,7 @@ class MqttClientImpl implements MqttClient {
}
void _onDisconnected() {
debugPrint('[MqttClient] disconnected callback');
debugPrint('${LogTime.now()} ⚠️ [$clientName] 连接断开');
_isConnected = false;
if (!_manualDisconnect) {
_scheduleReconnect();
@@ -234,7 +240,7 @@ class MqttClientImpl implements MqttClient {
}
void _onSubscribed(String topic) {
debugPrint('[MqttClient] subscribed: $topic');
debugPrint('${LogTime.now()} ✅ [$clientName] 订阅确认成功: $topic');
}
void _scheduleReconnect() {
@@ -246,12 +252,12 @@ class MqttClientImpl implements MqttClient {
if (_reconnectTimer?.isActive ?? false) return;
final delay = Duration(milliseconds: config.reconnectDelayMs);
debugPrint('[MqttClient] reconnect scheduled in ${delay.inMilliseconds}ms');
debugPrint('${LogTime.now()} ⏳ [$clientName] ${delay.inMilliseconds}ms 后尝试重连');
_reconnectTimer = Timer(delay, () async {
if (_manualDisconnect || _isConnected || _isConnecting) return;
try {
debugPrint('[MqttClient] reconnecting...');
debugPrint('${LogTime.now()} 🔄 [$clientName] 开始重连...');
await connect(config);
} catch (e) {
debugPrint('[MqttClient] reconnect failed: $e');

View File

@@ -0,0 +1,42 @@
import 'dart:async';
import 'package:fpdart/fpdart.dart';
import '../../../../../core/error/failure.dart';
import '../datasources/mower_realtime_datasource.dart';
import '../../domain/repositories/mower_realtime_repository.dart';
import '../../domain/entities/mower_location_entity.dart';
import '../../domain/entities/real_time_message_entity.dart';
import '../../domain/entities/route_status_entity.dart';
class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
final MowerRealtimeDataSource dataSource;
MowerRealtimeRepositoryImpl(this.dataSource);
@override
Stream<RealTimeMessageEntity> get vehicleStream => dataSource.vehicleStream;
@override
Stream<MowerLocationEntity> get locationStream => dataSource.locationStream;
@override
Stream<RouteStatusEntity> get routeStatusStream =>
dataSource.routeStatusStream;
@override
Future<Either<Failure, void>> startListening({
required String deviceSn,
}) async {
try {
await dataSource.startListening(deviceSn: deviceSn);
return right(null);
} catch (e) {
return left(Failure(e.toString()));
}
}
@override
Future<void> stopListening() async {
await dataSource.stopListening();
}
}