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

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',
);
}
}

View File

@@ -5,6 +5,8 @@ import 'package:equatable/equatable.dart';
/// 报文外层套一层信封,真正数据在 `data` 子对象(由 DataSource 提取后传入)。
/// 字段与后端 Java 实体一一对应,采用防御式解析,缺字段用默认值兜底。
class HostRealtimeMessageEntity extends Equatable {
final String? deviceSn;
final DateTime? receivedAt;
final double batteryPercentage; // 实时电量百分比
final double batteryVoltage; // 实时电压
final double leftMotorCurrent; // 实时左电机电流
@@ -19,7 +21,7 @@ class HostRealtimeMessageEntity extends Equatable {
final double totalWorkDuration; // 累计作业时长
final double totalWorkDistance; // 累计作业里程
final String motion; // moving|stopped|blocked 运动状态
final bool emergencyStop; // 急停状态
final bool? emergencyStop; // 急停状态;null 表示未上报或值无效
final double leftTargetRpm; // 实时左电机目标转速
final double rightTargetRpm; // 实时右电机目标转速
final double leftMeasuredRpm; // 实时左电机测量转速
@@ -35,6 +37,8 @@ class HostRealtimeMessageEntity extends Equatable {
final Map<String, dynamic> rawData;
const HostRealtimeMessageEntity({
this.deviceSn,
this.receivedAt,
this.batteryPercentage = 0,
this.batteryVoltage = 0,
this.leftMotorCurrent = 0,
@@ -49,7 +53,7 @@ class HostRealtimeMessageEntity extends Equatable {
this.totalWorkDuration = 0,
this.totalWorkDistance = 0,
this.motion = '',
this.emergencyStop = false,
this.emergencyStop,
this.leftTargetRpm = 0,
this.rightTargetRpm = 0,
this.leftMeasuredRpm = 0,
@@ -64,9 +68,16 @@ class HostRealtimeMessageEntity extends Equatable {
});
/// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致)
factory HostRealtimeMessageEntity.fromJson(Map<String, dynamic> data) {
factory HostRealtimeMessageEntity.fromJson(
Map<String, dynamic> data, {
String? deviceSn,
DateTime? receivedAt,
}) {
return HostRealtimeMessageEntity(
batteryPercentage: parseBatteryPercentage(data['battery_percentage']) ?? 0,
deviceSn: deviceSn,
receivedAt: receivedAt,
batteryPercentage:
parseBatteryPercentage(data['battery_percentage']) ?? 0,
batteryVoltage: _toDouble(data['battery_voltage']),
leftMotorCurrent: _toDouble(data['left_motor_current']),
rightMotorCurrent: _toDouble(data['right_motor_current']),
@@ -115,40 +126,43 @@ class HostRealtimeMessageEntity extends Equatable {
return double.tryParse(value.toString()) ?? 0;
}
static bool _toBool(dynamic value) {
if (value == null) return false;
static bool? _toBool(dynamic value) {
if (value is bool) return value;
if (value is num) return value != 0;
final s = value.toString().toLowerCase();
return s == 'true' || s == '1';
if (value == 1) return true;
if (value == 0) return false;
final s = value?.toString().trim().toLowerCase();
if (s == 'true' || s == '1') return true;
if (s == 'false' || s == '0') return false;
return null;
}
@override
List<Object?> get props => [
batteryPercentage,
batteryVoltage,
leftMotorCurrent,
rightMotorCurrent,
leftMotorTemperature,
rightMotorTemperature,
mainTemperature,
yaw,
pitch,
headingStatus,
totalWorkArea,
totalWorkDuration,
totalWorkDistance,
motion,
emergencyStop,
leftTargetRpm,
rightTargetRpm,
leftMeasuredRpm,
rightMeasuredRpm,
leftMotorRpm,
rightMotorRpm,
roll,
controlMode,
linearSpeed,
angularSpeed,
];
batteryPercentage,
batteryVoltage,
leftMotorCurrent,
rightMotorCurrent,
leftMotorTemperature,
rightMotorTemperature,
mainTemperature,
yaw,
pitch,
headingStatus,
totalWorkArea,
totalWorkDuration,
totalWorkDistance,
motion,
emergencyStop,
leftTargetRpm,
rightTargetRpm,
leftMeasuredRpm,
rightMeasuredRpm,
leftMotorRpm,
rightMotorRpm,
roll,
controlMode,
linearSpeed,
angularSpeed,
rawData,
];
}

View File

@@ -51,7 +51,7 @@ class DeviceDataPoint extends Equatable {
factory DeviceDataPoint.fromJson(Map<String, dynamic> json) {
return DeviceDataPoint(
name: json['name'] as String? ?? '',
value: json['value'] as String? ?? '',
value: json['value']?.toString() ?? '',
unit: json['unit'] as String? ?? '',
);
}