USB 摄像头+远程遥控+中英的适配+topic的集成和状态的使用到相应页面

This commit is contained in:
2026-10-20 17:03:37 +08:00
parent 178cd2533c
commit 582242e9aa
144 changed files with 15759 additions and 406 deletions

View File

@@ -8,6 +8,7 @@ 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';
import '../../domain/entities/host_realtime_message_entity.dart';
/// 割草机实时状态 MQTT 数据源(替代原 TCP 0x02 机器状态推送)
///
@@ -20,6 +21,9 @@ abstract class MowerRealtimeDataSource {
Stream<MowerLocationEntity> get locationStream;
Stream<RouteStatusEntity> get routeStatusStream;
/// 🔥 主机实时状态(device/{sn}/host/realTime/message,新增话题,纯附加)
Stream<HostRealtimeMessageEntity> get hostRealtimeStream;
/// 按设备 SN 启动订阅:自动退订旧设备主题、同 SN 去重
Future<void> startListening({required String deviceSn});
@@ -32,11 +36,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
static const String _realtimeSuffix = 'property/realtime/post';
static const String _locationSuffix = 'property/location/post';
static const String _routeSuffix = 'route/post';
static const String _hostRealtimeSuffix = 'host/realTime/message';
final _vehicleController =
StreamController<RealTimeMessageEntity>.broadcast();
final _locationController = StreamController<MowerLocationEntity>.broadcast();
final _routeController = StreamController<RouteStatusEntity>.broadcast();
final _hostRealtimeController =
StreamController<HostRealtimeMessageEntity>.broadcast();
StreamSubscription<MqttMessage>? _subscription;
@@ -47,6 +54,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
int _vehicleMsgCount = 0;
int _locationMsgCount = 0;
int _routeMsgCount = 0;
int _hostMsgCount = 0;
MowerRealtimeDataSourceImpl(this.mqttClient);
@@ -59,9 +67,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
@override
Stream<RouteStatusEntity> get routeStatusStream => _routeController.stream;
@override
Stream<HostRealtimeMessageEntity> get hostRealtimeStream =>
_hostRealtimeController.stream;
String _realtimeTopic(String sn) => 'mower/$sn/$_realtimeSuffix';
String _locationTopic(String sn) => 'mower/$sn/$_locationSuffix';
String _routeTopic(String sn) => 'device/$sn/$_routeSuffix';
String _hostRealtimeTopic(String sn) => 'device/$sn/$_hostRealtimeSuffix';
@override
Future<void> startListening({required String deviceSn}) async {
@@ -81,6 +94,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_realtimeTopic(_deviceSn!));
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn');
}
@@ -88,10 +102,12 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
_vehicleMsgCount = 0;
_locationMsgCount = 0;
_routeMsgCount = 0;
_hostMsgCount = 0;
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);
@@ -100,6 +116,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}');
debugPrint(' 定位: ${_locationTopic(deviceSn)}');
debugPrint(' 路径规划: ${_routeTopic(deviceSn)}');
debugPrint(' 主机实时: ${_hostRealtimeTopic(deviceSn)}');
}
@override
@@ -109,6 +126,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
await mqttClient.unsubscribe(_realtimeTopic(_deviceSn!));
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn');
_deviceSn = null;
}
@@ -153,6 +171,16 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
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(_hostRealtimeSuffix)) {
// 🔥 主机实时(新增话题,纯附加):外层套信封,数据在 json.data,提取方式与定位一致
_hostMsgCount++;
if (_hostMsgCount == 1) {
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}');
_hostRealtimeController.add(host);
} else if (message.topic.endsWith(_routeSuffix)) {
_routeMsgCount++;
if (_routeMsgCount == 1) {
@@ -174,5 +202,6 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
_vehicleController.close();
_locationController.close();
_routeController.close();
_hostRealtimeController.close();
}
}

View File

@@ -7,6 +7,7 @@ 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';
import '../../domain/entities/host_realtime_message_entity.dart';
class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
final MowerRealtimeDataSource dataSource;
@@ -23,6 +24,10 @@ class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
Stream<RouteStatusEntity> get routeStatusStream =>
dataSource.routeStatusStream;
@override
Stream<HostRealtimeMessageEntity> get hostRealtimeStream =>
dataSource.hostRealtimeStream;
@override
Future<Either<Failure, void>> startListening({
required String deviceSn,

View File

@@ -0,0 +1,132 @@
import 'package:equatable/equatable.dart';
/// 主机实时状态消息(MQTT 主题 device/{sn}/host/realTime/message)
///
/// 报文外层套一层信封,真正数据在 `data` 子对象(由 DataSource 提取后传入)。
/// 字段与后端 Java 实体一一对应,采用防御式解析,缺字段用默认值兜底。
class HostRealtimeMessageEntity extends Equatable {
final double batteryPercentage; // 实时电量百分比
final double batteryVoltage; // 实时电压
final double leftMotorCurrent; // 实时左电机电流
final double rightMotorCurrent; // 实时右电机电流
final double leftMotorTemperature; // 实时左电机温度
final double rightMotorTemperature; // 实时右电机温度
final double mainTemperature; // 实时主温度
final double yaw; // 实时航向角度
final double pitch; // 实时俯仰角度
final String headingStatus; // 实时航向状态
final double totalWorkArea; // 累计作业面积
final double totalWorkDuration; // 累计作业时长
final double totalWorkDistance; // 累计作业里程
final String motion; // moving|stopped|blocked 运动状态
final bool emergencyStop; // 急停状态
final double leftTargetRpm; // 实时左电机目标转速
final double rightTargetRpm; // 实时右电机目标转速
final double leftMeasuredRpm; // 实时左电机测量转速
final double rightMeasuredRpm; // 实时右电机测量转速
final double leftMotorRpm; // 实时左电机转速
final double rightMotorRpm; // 实时右电机转速
final double roll; // 实时翻滚角度
final String controlMode; // 当前控制模式(遥控器拨杆对应)
/// 原始 data 报文,便于后端补字段时兜底
final Map<String, dynamic> rawData;
const HostRealtimeMessageEntity({
this.batteryPercentage = 0,
this.batteryVoltage = 0,
this.leftMotorCurrent = 0,
this.rightMotorCurrent = 0,
this.leftMotorTemperature = 0,
this.rightMotorTemperature = 0,
this.mainTemperature = 0,
this.yaw = 0,
this.pitch = 0,
this.headingStatus = '',
this.totalWorkArea = 0,
this.totalWorkDuration = 0,
this.totalWorkDistance = 0,
this.motion = '',
this.emergencyStop = false,
this.leftTargetRpm = 0,
this.rightTargetRpm = 0,
this.leftMeasuredRpm = 0,
this.rightMeasuredRpm = 0,
this.leftMotorRpm = 0,
this.rightMotorRpm = 0,
this.roll = 0,
this.controlMode = '',
this.rawData = const {},
});
/// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致)
factory HostRealtimeMessageEntity.fromJson(Map<String, dynamic> data) {
return HostRealtimeMessageEntity(
batteryPercentage: _toDouble(data['battery_percentage']),
batteryVoltage: _toDouble(data['battery_voltage']),
leftMotorCurrent: _toDouble(data['left_motor_current']),
rightMotorCurrent: _toDouble(data['right_motor_current']),
leftMotorTemperature: _toDouble(data['left_motor_temperature']),
rightMotorTemperature: _toDouble(data['right_motor_temperature']),
mainTemperature: _toDouble(data['main_temperature']),
yaw: _toDouble(data['yaw']),
pitch: _toDouble(data['pitch']),
headingStatus: data['heading_status']?.toString() ?? '',
totalWorkArea: _toDouble(data['total_work_area']),
totalWorkDuration: _toDouble(data['total_work_duration']),
totalWorkDistance: _toDouble(data['total_work_distance']),
motion: data['motion']?.toString() ?? '',
emergencyStop: _toBool(data['emergency_stop']),
leftTargetRpm: _toDouble(data['left_target_rpm']),
rightTargetRpm: _toDouble(data['right_target_rpm']),
leftMeasuredRpm: _toDouble(data['left_measured_rpm']),
rightMeasuredRpm: _toDouble(data['right_measured_rpm']),
leftMotorRpm: _toDouble(data['left_motor_rpm']),
rightMotorRpm: _toDouble(data['right_motor_rpm']),
roll: _toDouble(data['roll']),
controlMode: data['control_mode']?.toString() ?? '',
rawData: data,
);
}
static double _toDouble(dynamic value) {
if (value == null) return 0;
if (value is num) return value.toDouble();
return double.tryParse(value.toString()) ?? 0;
}
static bool _toBool(dynamic value) {
if (value == null) return false;
if (value is bool) return value;
if (value is num) return value != 0;
final s = value.toString().toLowerCase();
return s == 'true' || s == '1';
}
@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,
];
}

View File

@@ -5,11 +5,13 @@ import '../../../../../core/error/failure.dart';
import '../entities/mower_location_entity.dart';
import '../entities/real_time_message_entity.dart';
import '../entities/route_status_entity.dart';
import '../entities/host_realtime_message_entity.dart';
abstract class MowerRealtimeRepository {
Stream<RealTimeMessageEntity> get vehicleStream;
Stream<MowerLocationEntity> get locationStream;
Stream<RouteStatusEntity> get routeStatusStream;
Stream<HostRealtimeMessageEntity> get hostRealtimeStream;
Future<Either<Failure, void>> startListening({
required String deviceSn,

View File

@@ -41,7 +41,10 @@ class TcpClient {
Timer? _heartbeatSendTimer; // 🔥 主动发送心跳定时器:每5秒给服务端发一次,防止服务端判定客户端失效
Timer? _reconnectTimer; // 重连定时器
int _reconnectAttempt = 0; // 🔥 重连尝试次数,用于退避计算
static const int _maxReconnectAttempts = 5; // 🔥 最大自动重连次数,防止网络不可达时无限重连
int _reconnectFailCount = 0; // 🔥 连续重连失败次数(含心跳超时),达到阈值后停止重连
int _reconnectFlapCount = 0; // 🔥 连续“连上又断”次数,识别成功-断开循环
static const int _maxReconnectFlaps = 5; // 🔥 最大允许连续成功-断开次数
/// 🔥 重连耗尽回调:连续4次重连失败(含心跳超时)后触发,通知上层弹窗提示用户
VoidCallback? onReconnectExhausted;
/// 🔥 重连开始回调:显示"TCP重连中"提示
@@ -156,6 +159,7 @@ class TcpClient {
_lastAuthPacketSentAt = null;
_reconnectAttempt = 0; // 🔥 重置重连退避
_reconnectFailCount = 0; // 🔥 重置重连失败计数
_reconnectFlapCount = 0; // 🔥 重置连上又断计数
// 5. 销毁 Socket
if (_socket != null) {
@@ -385,6 +389,15 @@ class TcpClient {
stopHeartbeat();
_socket = null;
// 🔥 每次断开都累计一次 flap(连上又断),识别成功-立即断开循环
_reconnectFlapCount++;
debugPrint('📊 [TCP] 连接断开次数: $_reconnectFlapCount/$_maxReconnectFlaps');
if (_reconnectFlapCount >= _maxReconnectFlaps) {
debugPrint('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连,通知用户退出登录');
_logger.logWithLevel('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连', shouldLog: true);
onReconnectExhausted?.call();
return;
}
// 🔥 连续失败达到4次,停止重连,通知上层弹窗
if (_reconnectFailCount >= 4) {
debugPrint('🛑 [TCP] 重连失败已达 4 次,停止重连,通知用户退出登录');
@@ -400,6 +413,14 @@ class TcpClient {
if (isUserSwitch) return;
if (_reconnectTimer != null) return;
// 🔥 限制总重连次数,防止网络不可达时无限重连
if (_reconnectAttempt >= _maxReconnectAttempts) {
debugPrint('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连,通知用户退出登录');
_logger.logWithLevel('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连', shouldLog: true);
onReconnectExhausted?.call();
return;
}
// 🔥 重连退避:5s → 10s → 20s → 30s(max)
final delay = [5, 10, 20, 30][_reconnectAttempt.clamp(0, 3)];
_reconnectAttempt++;
@@ -540,11 +561,31 @@ class TcpClient {
..addByte(0xAA)
..addByte(0xAB);
_socket!.add(builder.takeBytes());
// 🔥 关键修复:强制flush,确保数据立即发送
_socket!.flush();
final packet = builder.takeBytes();
try {
_socket!.add(packet);
// 🔥 关键修复:强制flush,确保数据立即发送
_socket!.flush();
// 联调日志:移到 add+flush 之后打印,证明这帧已真正交给系统 socket 发送缓冲
// ("发出去之后"才有参考价值;仍非后端 ACK,仅代表 App 侧写入成功)(联调结束可移除)
_logger.logWithLevel(
'🔗 [联调-TCP] sendRaw ✅已写入socket cmd=0x${cmd.toRadixString(16).padLeft(2, '0')} '
'len=${packet.length} frameHex=${_hex(packet)}',
shouldLog: true,
);
} catch (e) {
_logger.logWithLevel(
'🔗 [联调-TCP] sendRaw ❌写入socket失败 cmd=0x${cmd.toRadixString(16).padLeft(2, '0')} err=$e',
level: 'ERROR',
shouldLog: true,
);
}
}
/// 字节转十六进制字符串,供联调对包使用
String _hex(List<int> bytes) =>
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ');
void sendHeartbeat() {
if (_socket == null) return;
final builder = BytesBuilder()
@@ -580,6 +621,7 @@ class TcpClient {
/// 重置心跳超时定时器
/// 每次收到服务端心跳(0xFF)时调用,重新开始计时
void _resetHeartbeatTimeout() {
final wasRunning = _heartbeatTimer != null;
_heartbeatTimer?.cancel();
_heartbeatTimer = Timer(_heartbeatTimeout, () {
debugPrint('⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开');
@@ -595,6 +637,12 @@ class TcpClient {
// 🔥 统一走普通断开重连路径(_scheduleReconnect 已包含 HTTP switchDevice)
_handleDisconnect();
});
// 🔥 收到心跳说明连接真正稳定,重置“连上又断”计数
if (wasRunning && _reconnectFlapCount > 0) {
_reconnectFlapCount = 0;
debugPrint('📊 [TCP] 收到心跳,连接稳定,重置连接断开计数');
}
}
/// 🔥 封装完整的TCP初始化方法:连接 + 认证 + 心跳
@@ -784,6 +832,7 @@ class TcpClient {
_connectionCompleter = null;
_reconnectAttempt = 0; // 🔥 重置重连退避
_reconnectFailCount = 0; // 🔥 重置重连失败计数
_reconnectFlapCount = 0; // 🔥 重置连上又断计数
if (_socket != null) {
_socket!.destroy();
_socket = null;