完善遥控权限、控制发送和急停反馈

This commit is contained in:
2026-11-21 14:37:46 +08:00
parent c284aefc7d
commit 9a8a42a0a1
55 changed files with 5009 additions and 1308 deletions

View File

@@ -99,35 +99,37 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
controller = StreamController(
onListen: () {
// 先监听报文再订阅 Topic,接住订阅时立即到达的消息。
messageSubscription = messages.where((msg) => msg.topic == topic).listen(
(message) {
try {
final json = jsonDecode(message.payload);
if (json is! Map) return;
final payload = json['data'];
final data = payload is Map ? payload : json;
final battery = HostRealtimeMessageEntity.parseBatteryPercentage(
data['battery_percentage'],
);
lastBattery = battery ?? lastBattery;
controller.add(
(
battery: lastBattery,
controlMode: data['control_mode']?.toString().trim() ?? '',
),
);
} on FormatException {
// 忽略格式异常的单帧,等待下一次上报。
}
},
onError: controller.addError,
onDone: controller.close,
);
topicSubscription = mqttClient.subscribe(topic).catchError(
(Object error, StackTrace stackTrace) {
if (!controller.isClosed) controller.addError(error, stackTrace);
},
);
messageSubscription = messages
.where((msg) => msg.topic == topic)
.listen(
(message) {
try {
final json = jsonDecode(message.payload);
if (json is! Map) return;
final payload = json['data'];
final data = payload is Map ? payload : json;
final battery =
HostRealtimeMessageEntity.parseBatteryPercentage(
data['battery_percentage'],
);
lastBattery = battery ?? lastBattery;
controller.add((
battery: lastBattery,
controlMode: data['control_mode']?.toString().trim() ?? '',
));
} on FormatException {
// 忽略格式异常的单帧,等待下一次上报。
}
},
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();
@@ -154,7 +156,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 同一设备重复调用:去重,不重复订阅(参照 DroneOsdDataSource 已验证的模式)
if (_deviceSn == deviceSn && _subscription != null) {
debugPrint('${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn');
debugPrint(
'${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn',
);
return;
}
@@ -164,7 +168,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn');
debugPrint(
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn',
);
}
_deviceSn = deviceSn;
@@ -173,15 +179,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
_routeMsgCount = 0;
_hostMsgCount = 0;
// 先监听消息,接住订阅后立即到达的推送(包括 retained 消息)。
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
await mqttClient.subscribe(_realtimeTopic(deviceSn));
await mqttClient.subscribe(_locationTopic(deviceSn));
await mqttClient.subscribe(_routeTopic(deviceSn));
await mqttClient.subscribe(_hostRealtimeTopic(deviceSn));
// 消息流监听只建立一次,按 _deviceSn 过滤
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
debugPrint('${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn');
debugPrint(
'${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn',
);
debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}');
debugPrint(' 定位: ${_locationTopic(deviceSn)}');
debugPrint(' 路径规划: ${_routeTopic(deviceSn)}');
@@ -196,7 +204,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn');
debugPrint(
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn',
);
_deviceSn = null;
}
@@ -206,12 +216,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 防串台:只处理当前监听设备的主题(mower/ 和 device/ 前缀都要匹配)
if (!message.topic.contains('mower/$sn/') &&
!message.topic.contains('device/$sn/')) return;
!message.topic.contains('device/$sn/'))
return;
// 🔥 第一阶段:打印原始报文,确认格式后再完善解析
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] ──────── 收到消息 ────────');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] payload: ${message.payload}');
// 实时状态逐帧打印原始报文,在解析前确认急停字段是否实际下发。
if (message.topic == _realtimeTopic(sn) ||
message.topic == _hostRealtimeTopic(sn)) {
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
debugPrint('[MQTT-机器状态] payload 开始');
debugPrint(message.payload, wrapWidth: 800);
debugPrint('[MQTT-机器状态] payload 结束');
}
try {
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
@@ -224,9 +239,13 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
if (_vehicleMsgCount == 1) {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 车辆实时首帧到达: $sn');
}
debugPrint('${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个');
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}');
debugPrint(
'${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}',
);
}
_vehicleController.add(vehicle);
}
@@ -238,7 +257,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
// 🔥 关键修复:坐标在 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}');
// 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(_hostRealtimeSuffix)) {
// 🔥 主机实时(新增话题,纯附加):外层套信封,数据在 json.data,提取方式与定位一致
@@ -247,8 +266,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
debugPrint('${LogTime.now()} 🎉 [MQTT-主机实时] 首帧到达: $sn');
}
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
final host = HostRealtimeMessageEntity.fromJson(dataObj);
debugPrint('${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 急停=${host.emergencyStop} 运动=${host.motion}');
final host = HostRealtimeMessageEntity.fromJson(
dataObj,
deviceSn: sn,
receivedAt: message.timestamp,
);
debugPrint(
'${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} emergency_stop存在=${dataObj.containsKey('emergency_stop')} 原始值=${dataObj['emergency_stop']} 急停解析值=${host.emergencyStop} 运动=${host.motion}',
);
_hostRealtimeController.add(host);
} else if (message.topic.endsWith(_routeSuffix)) {
_routeMsgCount++;
@@ -256,11 +281,15 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 路径规划首帧到达: $sn');
}
final routeMsg = RouteStatusEntity.fromJson(jsonData);
debugPrint('${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}');
debugPrint(
'${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}',
);
_routeController.add(routeMsg);
}
} catch (e) {
debugPrint('${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败: $e');
debugPrint(
'${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败 topic=${message.topic}: $e',
);
}
}