完善遥控权限、控制发送和急停反馈
This commit is contained in:
@@ -7,6 +7,7 @@ import '../../../../core/localization/app_localizations.dart';
|
||||
import '../../domain/entities/device_control_mode.dart';
|
||||
import '../../domain/usecases/device_control_mode_usecases.dart';
|
||||
import '../cubit/control_mode_entry_cubit.dart';
|
||||
import 'mode_independent_control.dart';
|
||||
|
||||
Future<bool> showControlModeEntryDialog(
|
||||
BuildContext context, {
|
||||
@@ -15,6 +16,7 @@ Future<bool> showControlModeEntryDialog(
|
||||
String? deviceName,
|
||||
bool allowTargetSelection = false,
|
||||
bool cancelToPreview = false,
|
||||
Widget? emergencyStopControl,
|
||||
ControlModeEntryCubit? cubit,
|
||||
}) async {
|
||||
final entry =
|
||||
@@ -34,6 +36,7 @@ Future<bool> showControlModeEntryDialog(
|
||||
backgroundColor: Colors.transparent,
|
||||
barrierColor: const Color(0x8C0B1B2B),
|
||||
isScrollControlled: true,
|
||||
constraints: const BoxConstraints(maxWidth: 440),
|
||||
isDismissible: false,
|
||||
enableDrag: false,
|
||||
builder: (_) => BlocProvider.value(
|
||||
@@ -42,6 +45,7 @@ Future<bool> showControlModeEntryDialog(
|
||||
deviceName: deviceName,
|
||||
allowTargetSelection: allowTargetSelection,
|
||||
cancelToPreview: cancelToPreview,
|
||||
emergencyStopControl: emergencyStopControl,
|
||||
),
|
||||
),
|
||||
) ??
|
||||
@@ -61,6 +65,7 @@ class ControlModeEntryGate extends StatefulWidget {
|
||||
this.deviceName,
|
||||
this.onReady,
|
||||
this.cancelToPreview = false,
|
||||
this.emergencyStopControl,
|
||||
});
|
||||
final String deviceId;
|
||||
final String? deviceName;
|
||||
@@ -68,6 +73,9 @@ class ControlModeEntryGate extends StatefulWidget {
|
||||
final Widget child;
|
||||
final VoidCallback? onReady;
|
||||
final bool cancelToPreview;
|
||||
|
||||
/// 独立急停链路,不受控制模式确认限制。
|
||||
final Widget? emergencyStopControl;
|
||||
@override
|
||||
State<ControlModeEntryGate> createState() => _ControlModeEntryGateState();
|
||||
}
|
||||
@@ -93,6 +101,7 @@ class _ControlModeEntryGateState extends State<ControlModeEntryGate> {
|
||||
deviceName: widget.deviceName,
|
||||
target: widget.target,
|
||||
cancelToPreview: widget.cancelToPreview,
|
||||
emergencyStopControl: widget.emergencyStopControl,
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (accepted) {
|
||||
@@ -115,7 +124,7 @@ class _ControlModeEntryGateState extends State<ControlModeEntryGate> {
|
||||
children: [
|
||||
ExcludeFocus(
|
||||
excluding: !_ready,
|
||||
child: IgnorePointer(ignoring: !_ready, child: widget.child),
|
||||
child: ControlModePointerGate(blocked: !_ready, child: widget.child),
|
||||
),
|
||||
if (_cancelled && widget.cancelToPreview)
|
||||
_buildPreviewControls(context)
|
||||
@@ -208,6 +217,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
this.deviceName,
|
||||
this.allowTargetSelection = false,
|
||||
this.cancelToPreview = false,
|
||||
this.emergencyStopControl,
|
||||
});
|
||||
|
||||
static const _navy = Color(0xFF1A2B4A);
|
||||
@@ -220,6 +230,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
final String? deviceName;
|
||||
final bool allowTargetSelection;
|
||||
final bool cancelToPreview;
|
||||
final Widget? emergencyStopControl;
|
||||
|
||||
Widget _modeCard({
|
||||
required String label,
|
||||
@@ -228,7 +239,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
bool target = false,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: target ? _softBlue : const Color(0xFFF6FAFE),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
@@ -237,15 +248,15 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
width: 30,
|
||||
height: 30,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(icon, color: _blue, size: 21),
|
||||
child: Icon(icon, color: _blue, size: 18),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -258,7 +269,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: _navy,
|
||||
),
|
||||
@@ -341,7 +352,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(18, 16, 18, 16),
|
||||
padding: const EdgeInsets.fromLTRB(16, 10, 16, 12),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
@@ -354,12 +365,14 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
allowTargetSelection ? 'switch_title' : 'title',
|
||||
),
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontSize: 17,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _navy,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (emergencyStopControl != null)
|
||||
emergencyStopControl!,
|
||||
IconButton(
|
||||
tooltip: cancelToPreview
|
||||
? cancelText
|
||||
@@ -392,27 +405,37 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_modeCard(
|
||||
label: tr('current'),
|
||||
value: controlModeDisplayText(
|
||||
l10n,
|
||||
state.reading?.rawMode,
|
||||
),
|
||||
icon: Icons.sensors_rounded,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
// 自主任务选项继续停用,由后端处理;这里展示本次确认的目标。
|
||||
_modeCard(
|
||||
label: tr(
|
||||
allowTargetSelection ? 'selection_target' : 'target',
|
||||
),
|
||||
value:
|
||||
allowTargetSelection &&
|
||||
cubit.target == ControlModeTarget.remote
|
||||
? tr('switch_manual')
|
||||
: targetText,
|
||||
icon: Icons.swap_horiz_rounded,
|
||||
target: true,
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: _modeCard(
|
||||
label: tr('current'),
|
||||
value: controlModeDisplayText(
|
||||
l10n,
|
||||
state.reading?.rawMode,
|
||||
),
|
||||
icon: Icons.sensors_rounded,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: _modeCard(
|
||||
label: tr(
|
||||
allowTargetSelection
|
||||
? 'selection_target'
|
||||
: 'target',
|
||||
),
|
||||
value:
|
||||
allowTargetSelection &&
|
||||
cubit.target == ControlModeTarget.remote
|
||||
? tr('switch_manual')
|
||||
: targetText,
|
||||
icon: Icons.swap_horiz_rounded,
|
||||
target: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
@@ -438,7 +461,9 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
note,
|
||||
cubit.target == ControlModeTarget.remote
|
||||
? '$note\n${tr('remote_retry_hint')}'
|
||||
: note,
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.5,
|
||||
@@ -478,7 +503,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
style: TextButton.styleFrom(foregroundColor: _blue),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
@@ -487,7 +512,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
icon: const Icon(Icons.close_rounded, size: 18),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: _blue,
|
||||
minimumSize: const Size.fromHeight(48),
|
||||
minimumSize: const Size.fromHeight(40),
|
||||
side: BorderSide(
|
||||
color: canCancel ? _blue : _border,
|
||||
width: 1.2,
|
||||
@@ -516,7 +541,7 @@ class _ControlModeEntryDialog extends StatelessWidget {
|
||||
0xFFDCEBFA,
|
||||
),
|
||||
disabledForegroundColor: _gray,
|
||||
minimumSize: const Size.fromHeight(48),
|
||||
minimumSize: const Size.fromHeight(40),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// 保持控件原位,标记独立于模式确认的操作区(如急停、页面设置)。
|
||||
class ModeIndependentControl extends SingleChildRenderObjectWidget {
|
||||
const ModeIndependentControl({super.key, required super.child});
|
||||
|
||||
@override
|
||||
RenderProxyBox createRenderObject(BuildContext context) =>
|
||||
_IndependentRegion();
|
||||
}
|
||||
|
||||
class _IndependentRegion extends RenderProxyBox {}
|
||||
|
||||
/// 模式未确认时,只将指针事件交给原布局中明确标记的独立操作区。
|
||||
class ControlModePointerGate extends SingleChildRenderObjectWidget {
|
||||
const ControlModePointerGate({
|
||||
super.key,
|
||||
required this.blocked,
|
||||
required super.child,
|
||||
});
|
||||
final bool blocked;
|
||||
|
||||
@override
|
||||
RenderProxyBox createRenderObject(BuildContext context) =>
|
||||
_PointerGate(blocked);
|
||||
|
||||
@override
|
||||
void updateRenderObject(
|
||||
BuildContext context,
|
||||
covariant _PointerGate renderObject,
|
||||
) {
|
||||
renderObject.blocked = blocked;
|
||||
}
|
||||
}
|
||||
|
||||
class _PointerGate extends RenderProxyBox {
|
||||
_PointerGate(this.blocked);
|
||||
bool blocked;
|
||||
|
||||
@override
|
||||
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
|
||||
if (!blocked) return super.hitTestChildren(result, position: position);
|
||||
var hit = false;
|
||||
void visit(RenderObject node) {
|
||||
if (hit) return;
|
||||
if (node is _IndependentRegion && node.attached && node.hasSize) {
|
||||
hit = result.addWithPaintTransform(
|
||||
transform: node.getTransformTo(this),
|
||||
position: position,
|
||||
hitTest: (result, position) =>
|
||||
node.hitTest(result, position: position),
|
||||
);
|
||||
return;
|
||||
}
|
||||
node.visitChildren(visit);
|
||||
}
|
||||
|
||||
final content = child;
|
||||
if (content != null) visit(content);
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../domain/entities/emergency_stop_target.dart';
|
||||
|
||||
class EmergencyStopRemoteDatasource {
|
||||
const EmergencyStopRemoteDatasource(this.dio);
|
||||
// 注入统一 Dio,沿用登录鉴权和测试/生产环境配置。
|
||||
final Dio dio;
|
||||
|
||||
Future<void> request(String deviceId, EmergencyStopTarget target) async {
|
||||
final response = await dio.get<dynamic>(
|
||||
HttpApiConsts.hostEmergencyStopChange,
|
||||
queryParameters: {'deviceId': deviceId, 'eStop': target.value},
|
||||
options: Options(
|
||||
receiveTimeout: const Duration(seconds: 10),
|
||||
headers: {'Cache-Control': 'no-store', 'Pragma': 'no-cache'},
|
||||
),
|
||||
);
|
||||
final body = response.data;
|
||||
// 沿用相邻 /iot/host 接口的业务响应约定;未知响应不视为成功。
|
||||
if (response.statusCode != 200 || body is! Map || body['code'] == null) {
|
||||
throw const EmergencyStopRemoteException('急停接口响应格式错误或请求失败');
|
||||
}
|
||||
final data = body['data'];
|
||||
if ('${body['code']}' != '200' ||
|
||||
data == false ||
|
||||
body['accepted'] == false ||
|
||||
(data is Map && data['accepted'] == false)) {
|
||||
final message = body['msg'];
|
||||
throw EmergencyStopRemoteException(
|
||||
message is String && message.trim().isNotEmpty ? message : '急停请求未被接受',
|
||||
rejected: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class EmergencyStopRemoteException implements Exception {
|
||||
const EmergencyStopRemoteException(this.message, {this.rejected = false});
|
||||
final String message;
|
||||
final bool rejected;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/emergency_stop_target.dart';
|
||||
import '../../domain/entities/emergency_stop_failure.dart';
|
||||
import '../../domain/repositories/device_emergency_stop_repository.dart';
|
||||
import '../datasources/emergency_stop_remote_datasource.dart';
|
||||
|
||||
class DeviceEmergencyStopRepositoryImpl
|
||||
implements DeviceEmergencyStopRepository {
|
||||
const DeviceEmergencyStopRepositoryImpl(this.remote);
|
||||
final EmergencyStopRemoteDatasource remote;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Unit>> request(
|
||||
String deviceId,
|
||||
EmergencyStopTarget target,
|
||||
) async {
|
||||
try {
|
||||
await remote.request(deviceId, target);
|
||||
return const Right(unit);
|
||||
} on EmergencyStopRemoteException catch (error) {
|
||||
return Left(
|
||||
error.rejected
|
||||
? EmergencyStopRejectedFailure(error.message)
|
||||
: ServerFailure(error.message),
|
||||
);
|
||||
} on DioException catch (error) {
|
||||
final status = error.response?.statusCode;
|
||||
if (status == 401 || status == 403) {
|
||||
return Left(EmergencyStopRejectedFailure('登录已失效或无权执行急停操作'));
|
||||
}
|
||||
if (error.type == DioExceptionType.connectionTimeout ||
|
||||
error.type == DioExceptionType.sendTimeout ||
|
||||
error.type == DioExceptionType.receiveTimeout) {
|
||||
return Left(NetworkFailure('急停请求超时,执行结果未确认'));
|
||||
}
|
||||
if (error.response != null) {
|
||||
return Left(ServerFailure('急停接口请求失败'));
|
||||
}
|
||||
return Left(NetworkFailure('急停请求连接异常,执行结果未确认'));
|
||||
} catch (_) {
|
||||
return Left(Failure('急停请求异常,执行结果未确认'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import '../../../../core/error/failure.dart';
|
||||
|
||||
/// 后端明确返回业务失败,区别于断线/超时导致的结果未知。
|
||||
class EmergencyStopRejectedFailure extends ServerFailure {
|
||||
EmergencyStopRejectedFailure(super.message);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// 请求目标,不代表设备已经执行;实际急停状态仍以设备反馈为准。
|
||||
enum EmergencyStopTarget {
|
||||
engage(1),
|
||||
release(0);
|
||||
|
||||
const EmergencyStopTarget(this.value);
|
||||
final int value;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/emergency_stop_target.dart';
|
||||
|
||||
abstract class DeviceEmergencyStopRepository {
|
||||
/// 成功仅表示接口接受请求,不确认车辆实际急停或解除。
|
||||
Future<Either<Failure, Unit>> request(
|
||||
String deviceId,
|
||||
EmergencyStopTarget target,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/emergency_stop_target.dart';
|
||||
import '../repositories/device_emergency_stop_repository.dart';
|
||||
|
||||
class RequestDeviceEmergencyStopUseCase {
|
||||
const RequestDeviceEmergencyStopUseCase(this.repository);
|
||||
final DeviceEmergencyStopRepository repository;
|
||||
|
||||
Future<Either<Failure, Unit>> call(
|
||||
String deviceId,
|
||||
EmergencyStopTarget target,
|
||||
) {
|
||||
final id = deviceId.trim();
|
||||
if (id.isEmpty) return Future.value(Left(Failure('设备标识不能为空')));
|
||||
return repository.request(id, target);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import '../../../../core/network/mqtt/domain/entities/host_realtime_message_entity.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
|
||||
class RunningStatusEntity extends Equatable {
|
||||
static const _unchanged = Object();
|
||||
|
||||
// === 基础电气信息 (字段 0-6) ===
|
||||
final double voltage; // [0] 电压 (V)
|
||||
final double leftTargetSpeed; // [1] 左轮目标速度
|
||||
@@ -50,6 +53,9 @@ class RunningStatusEntity extends Equatable {
|
||||
final double linearSpeed; // host 实时线速度 m/s(前进为正,后退为负)
|
||||
final double angularSpeed; // host 实时角速度 rad/s(左转为正,右转为负)
|
||||
final bool hostDataReceived; // 是否已收到 host 实时数据(未收到时 UI 显示"未知")
|
||||
final bool? emergencyStop; // 本帧急停状态;null 表示没有有效上报
|
||||
/// 保留本帧字段是否存在,遥控 HUD 据此区分真实零值和未上报。
|
||||
final HostRealtimeMessageEntity? hostRealtime;
|
||||
|
||||
const RunningStatusEntity({
|
||||
this.voltage = 0.0,
|
||||
@@ -71,7 +77,7 @@ class RunningStatusEntity extends Equatable {
|
||||
this.latitude = 0.0,
|
||||
this.longitude = 0.0,
|
||||
this.timestamp = '',
|
||||
this.knifeCuttingSpeed = '0',
|
||||
this.knifeCuttingSpeed = '',
|
||||
this.controlMode = '',
|
||||
this.battery = '0',
|
||||
this.workingArea = '0',
|
||||
@@ -80,6 +86,8 @@ class RunningStatusEntity extends Equatable {
|
||||
this.linearSpeed = 0.0,
|
||||
this.angularSpeed = 0.0,
|
||||
this.hostDataReceived = false,
|
||||
this.emergencyStop,
|
||||
this.hostRealtime,
|
||||
});
|
||||
|
||||
/// 从字段数组创建实体 (核心解析方法)
|
||||
@@ -145,7 +153,7 @@ class RunningStatusEntity extends Equatable {
|
||||
|
||||
// 扩展信息 (保持原始字符串,由调用方决定如何解析)
|
||||
timestamp: fields[18].trim(),
|
||||
knifeCuttingSpeed: fields[19].trim().isNotEmpty ? fields[19].trim() : '0',
|
||||
knifeCuttingSpeed: fields[19].trim(),
|
||||
// 空串原样保留:表示后端这一帧没带该字段,UI 据此显示「未知」
|
||||
controlMode: fields[20].trim(),
|
||||
battery: fields[21].trim().isNotEmpty ? fields[21].trim() : '0',
|
||||
@@ -184,6 +192,8 @@ class RunningStatusEntity extends Equatable {
|
||||
double? linearSpeed,
|
||||
double? angularSpeed,
|
||||
bool? hostDataReceived,
|
||||
Object? emergencyStop = _unchanged,
|
||||
HostRealtimeMessageEntity? hostRealtime,
|
||||
}) {
|
||||
return RunningStatusEntity(
|
||||
voltage: voltage ?? this.voltage,
|
||||
@@ -214,6 +224,10 @@ class RunningStatusEntity extends Equatable {
|
||||
linearSpeed: linearSpeed ?? this.linearSpeed,
|
||||
angularSpeed: angularSpeed ?? this.angularSpeed,
|
||||
hostDataReceived: hostDataReceived ?? this.hostDataReceived,
|
||||
hostRealtime: hostRealtime ?? this.hostRealtime,
|
||||
emergencyStop: identical(emergencyStop, _unchanged)
|
||||
? this.emergencyStop
|
||||
: emergencyStop as bool?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -247,6 +261,8 @@ class RunningStatusEntity extends Equatable {
|
||||
linearSpeed,
|
||||
angularSpeed,
|
||||
hostDataReceived,
|
||||
emergencyStop,
|
||||
hostRealtime,
|
||||
];
|
||||
|
||||
@override
|
||||
|
||||
@@ -12,6 +12,7 @@ import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_e
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../../core/logging/remote_control_diagnostics.dart';
|
||||
import '../../../../core/logging/log_time.dart';
|
||||
import '../../../../core/network/net_message_dispatcher.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
@@ -60,6 +61,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
/// 当前实时快照的设备身份,供入口模式确认使用(只读)。
|
||||
String? get listeningDeviceSn => _currentListeningSn;
|
||||
|
||||
/// 仅由主机帧刷新,定位/其他状态不会延长急停状态有效期。
|
||||
({String sn, bool? active, DateTime receivedAt})? emergencyStopReading;
|
||||
|
||||
// 🔥 MQTT机器状态收帧计数(用于链路日志)
|
||||
int _mqttVehicleFrameCount = 0;
|
||||
int _mqttLocationFrameCount = 0;
|
||||
@@ -125,7 +129,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
final is02 = p.command == 0x02;
|
||||
if (is02) {
|
||||
_packetSeq++;
|
||||
debugPrint('📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}');
|
||||
debugPrint(
|
||||
'📥 [0x02] #$_packetSeq 收到原始TCP包 | payload长度=${p.payload.length} | ${DateTime.now().toString().substring(11, 19)}',
|
||||
);
|
||||
}
|
||||
return is02;
|
||||
})
|
||||
@@ -134,7 +140,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
final result = utf8.decode(p.payload, allowMalformed: true);
|
||||
return result;
|
||||
} catch (e) {
|
||||
debugPrint('❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}');
|
||||
debugPrint(
|
||||
'❌ [0x02] #$_packetSeq 解码失败: $e, payload前20字节=${p.payload.take(20).toList()}',
|
||||
);
|
||||
return '';
|
||||
}
|
||||
})
|
||||
@@ -150,7 +158,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
final fields = message.trim().split(',');
|
||||
|
||||
if (fields.length < 18) {
|
||||
debugPrint('⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}');
|
||||
debugPrint(
|
||||
'⚠️ [0x02] #$_packetSeq 字段不足:${fields.length},期望≥18, 原始数据前100字符=${message.substring(0, message.length > 100 ? 100 : message.length)}',
|
||||
);
|
||||
// 🔥 错误不节流,立即emit以便UI显示错误
|
||||
if (!isClosed) {
|
||||
emit(DeviceStatusError('字段不足,期望≥18,实际:${fields.length}'));
|
||||
@@ -161,7 +171,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
final status = RunningStatusEntity.fromFields(fields);
|
||||
final gps = GPSEntity(status.latitude, status.longitude);
|
||||
|
||||
debugPrint('✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms');
|
||||
debugPrint(
|
||||
'✅ [0x02] #$_packetSeq 解析成功 | 字段数=${fields.length} | 电压=${status.voltage}V 电量=${status.battery}% 控制模式=${status.controlMode} | 节流等待${_throttleDuration.inMilliseconds}ms',
|
||||
);
|
||||
|
||||
// 🔥 缓存最新数据用于节流发射
|
||||
_cachedStatus = RunningStatusEntity(
|
||||
@@ -228,11 +240,14 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
return;
|
||||
}
|
||||
|
||||
debugPrint('${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🚀 [DeviceStatusBloc] 启动MQTT机器状态监听: $deviceSn',
|
||||
);
|
||||
|
||||
// 🔥 换设备兜底:SN 变化时清空上一个设备的缓存与状态,
|
||||
// 防止旧坐标通过 copyWith(base) 残留污染新设备数据(即使入口漏调 Reset 也能兜住)
|
||||
if (_currentListeningSn != deviceSn) {
|
||||
emergencyStopReading = null;
|
||||
_throttleTimer?.cancel();
|
||||
_throttleTimer = null;
|
||||
_cachedStatus = null;
|
||||
@@ -241,7 +256,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
if (!isClosed) {
|
||||
emit(DeviceStatusInitial());
|
||||
}
|
||||
debugPrint('${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🧹 [DeviceStatusBloc] 切换设备,已清空旧缓存: $deviceSn',
|
||||
);
|
||||
}
|
||||
|
||||
// 按SN订阅(数据源内部自动退旧订新、同SN去重)
|
||||
@@ -268,16 +285,27 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
debugPrint(
|
||||
'${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_mqttVehicleFrameCount帧 type=${message.type} 数据点=${message.data.length}',
|
||||
);
|
||||
// TODO 第二阶段:将数据点映射到 RunningStatusEntity 字段,复用500ms节流emit
|
||||
// 沿用车辆数据点现有 cuttingSpeed 字段;主机话题没有割刀反馈。
|
||||
// 缺失或非法时清空,不能把默认 0 当成设备已停刀。
|
||||
final cutterRpm = message.getValueByName('cuttingSpeed');
|
||||
final base = _cachedStatus ?? const RunningStatusEntity();
|
||||
_cachedStatus = base.copyWith(
|
||||
knifeCuttingSpeed: cutterRpm != null && cutterRpm.isFinite
|
||||
? cutterRpm.toString()
|
||||
: '',
|
||||
);
|
||||
if (_throttleTimer == null || !_throttleTimer!.isActive) {
|
||||
_throttleTimer = Timer(_throttleDuration, _emitCachedStatus);
|
||||
}
|
||||
});
|
||||
|
||||
_mqttLocationSubscription ??= _mowerRealtimeRepo.locationStream.listen((
|
||||
location,
|
||||
) {
|
||||
_mqttLocationFrameCount++;
|
||||
debugPrint(
|
||||
'${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}',
|
||||
);
|
||||
// debugPrint(
|
||||
// '${LogTime.now()} 📍 [MQTT-location] 定位第$_mqttLocationFrameCount帧 lat=${location.latitude}, lng=${location.longitude}, heading=${location.heading}',
|
||||
// );
|
||||
|
||||
// 🔥 核心:用 MQTT location 数据更新缓存并节流 emit
|
||||
if (location.isValid) {
|
||||
@@ -310,6 +338,50 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
_mqttHostSubscription ??= _mowerRealtimeRepo.hostRealtimeStream.listen((
|
||||
host,
|
||||
) {
|
||||
final sn = _currentListeningSn;
|
||||
if (host.deviceSn != null && host.deviceSn != sn) return;
|
||||
if (sn != null) {
|
||||
emergencyStopReading = (
|
||||
sn: sn,
|
||||
active: host.emergencyStop,
|
||||
receivedAt: host.receivedAt ?? DateTime.now(),
|
||||
);
|
||||
}
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
if (trace.activeDevice != null &&
|
||||
trace.activeDevice == _currentListeningSn) {
|
||||
final raw = host.rawData;
|
||||
trace.event('host_telemetry', {
|
||||
'telemetryDevice': _currentListeningSn,
|
||||
'linearMps': raw.containsKey('linear_speed')
|
||||
? host.linearSpeed
|
||||
: null,
|
||||
'angularRadps': raw.containsKey('angular_speed')
|
||||
? host.angularSpeed
|
||||
: null,
|
||||
'leftTargetRpm': raw.containsKey('left_target_rpm')
|
||||
? host.leftTargetRpm
|
||||
: null,
|
||||
'rightTargetRpm': raw.containsKey('right_target_rpm')
|
||||
? host.rightTargetRpm
|
||||
: null,
|
||||
'leftMeasuredRpm': raw.containsKey('left_measured_rpm')
|
||||
? host.leftMeasuredRpm
|
||||
: null,
|
||||
'rightMeasuredRpm': raw.containsKey('right_measured_rpm')
|
||||
? host.rightMeasuredRpm
|
||||
: null,
|
||||
'leftCurrent': raw.containsKey('left_motor_current')
|
||||
? host.leftMotorCurrent
|
||||
: null,
|
||||
'rightCurrent': raw.containsKey('right_motor_current')
|
||||
? host.rightMotorCurrent
|
||||
: null,
|
||||
'emergency': raw['emergency_stop'],
|
||||
'controlMode': raw['control_mode'],
|
||||
'motion': raw['motion'],
|
||||
});
|
||||
}
|
||||
final base = _cachedStatus ?? RunningStatusEntity();
|
||||
_cachedStatus = base.copyWith(
|
||||
voltage: host.batteryVoltage,
|
||||
@@ -331,6 +403,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
// 代价:若 host 帧偶发漏带该字段,此栏会在真值与「未知」间跳动;
|
||||
// 现场若出现闪烁,说明 host 帧字段不稳定,应从后端侧解决而非在此兜底。
|
||||
controlMode: host.controlMode,
|
||||
emergencyStop: host.emergencyStop,
|
||||
workingArea: host.totalWorkArea.toString(),
|
||||
// 🔥 供全功能模式(pv_control)展示:累计作业里程 + host 已推数据标记
|
||||
totalWorkDistance: host.totalWorkDistance,
|
||||
@@ -338,15 +411,19 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
linearSpeed: host.linearSpeed,
|
||||
angularSpeed: host.angularSpeed,
|
||||
hostDataReceived: true,
|
||||
hostRealtime: host,
|
||||
);
|
||||
|
||||
// 🔥 host 无坐标:GPS 缺省时用当前经纬度占位,保证能即时刷新(不覆盖 location 已写入的真坐标)
|
||||
_cachedGps ??= GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude);
|
||||
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s',
|
||||
_cachedGps ??= GPSEntity(
|
||||
_cachedStatus!.latitude,
|
||||
_cachedStatus!.longitude,
|
||||
);
|
||||
|
||||
// debugPrint(
|
||||
// '${LogTime.now()} 🛰️ [MQTT-主机实时] 已合并 → 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 线速度=${host.linearSpeed}m/s 角速度=${host.angularSpeed}rad/s',
|
||||
// );
|
||||
|
||||
// 500ms 节流:与 location/车辆实时 发射链路一致
|
||||
if (_throttleTimer == null || !_throttleTimer!.isActive) {
|
||||
_throttleTimer = Timer(_throttleDuration, () {
|
||||
@@ -355,7 +432,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
}
|
||||
});
|
||||
|
||||
debugPrint('${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} ✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn',
|
||||
);
|
||||
_logger.log('✅ [DeviceStatusBloc] MQTT机器状态监听已启动: $deviceSn');
|
||||
}
|
||||
|
||||
@@ -440,10 +519,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
|
||||
// 🔥 无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建
|
||||
if (!isClosed) {
|
||||
emit(DeviceStatusUpdated(
|
||||
_cachedStatus ?? RunningStatusEntity(),
|
||||
_cachedGps ?? GPSEntity(0.0, 0.0),
|
||||
));
|
||||
emit(
|
||||
DeviceStatusUpdated(
|
||||
_cachedStatus ?? RunningStatusEntity(),
|
||||
_cachedGps ?? GPSEntity(0.0, 0.0),
|
||||
),
|
||||
);
|
||||
debugPrint('📤 [DeviceStatusBloc] 已 emit 完成信号,触发 UI 更新');
|
||||
}
|
||||
|
||||
@@ -473,17 +554,28 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
int _fixStatusToQual(String? fixStatus, int fallback) {
|
||||
if (fixStatus == null) return fallback;
|
||||
switch (fixStatus) {
|
||||
case 'no_fix': return 0;
|
||||
case 'single': return 1;
|
||||
case 'dgnss': return 2;
|
||||
case 'ins': return 3;
|
||||
case 'rtk_fixed': return 4;
|
||||
case 'rtk_float': return 5;
|
||||
case 'single_no_heading': return 6;
|
||||
case 'dgnss_no_heading': return 7;
|
||||
case 'rtk_fixed_no_heading': return 8;
|
||||
case 'rtk_float_no_heading': return 9;
|
||||
default: return fallback;
|
||||
case 'no_fix':
|
||||
return 0;
|
||||
case 'single':
|
||||
return 1;
|
||||
case 'dgnss':
|
||||
return 2;
|
||||
case 'ins':
|
||||
return 3;
|
||||
case 'rtk_fixed':
|
||||
return 4;
|
||||
case 'rtk_float':
|
||||
return 5;
|
||||
case 'single_no_heading':
|
||||
return 6;
|
||||
case 'dgnss_no_heading':
|
||||
return 7;
|
||||
case 'rtk_fixed_no_heading':
|
||||
return 8;
|
||||
case 'rtk_float_no_heading':
|
||||
return 9;
|
||||
default:
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,13 +583,14 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
// 🔥 放宽:允许仅有机器状态(host 先到、GPS 未到)时也能刷新 UI
|
||||
void _emitCachedStatus() {
|
||||
if (_cachedStatus != null && !isClosed) {
|
||||
final gps = _cachedGps ??
|
||||
final gps =
|
||||
_cachedGps ??
|
||||
GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude);
|
||||
// 控制模式为空串 = 后端从未给过,日志里显式标出来,免得和 0 混看
|
||||
final controlModeLog = _cachedStatus!.controlMode.isEmpty
|
||||
? '--(未收到)'
|
||||
: _cachedStatus!.controlMode;
|
||||
debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}');
|
||||
// final controlModeLog = _cachedStatus!.controlMode.isEmpty
|
||||
// ? '--(未收到)'
|
||||
// : _cachedStatus!.controlMode;
|
||||
// debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}');
|
||||
emit(DeviceStatusUpdated(_cachedStatus!, gps));
|
||||
}
|
||||
}
|
||||
@@ -507,6 +600,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
DeviceStatusReset event,
|
||||
Emitter<DeviceStatusState> emit,
|
||||
) async {
|
||||
emergencyStopReading = null;
|
||||
debugPrint('🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}');
|
||||
_logger.log(
|
||||
'🔄 [DeviceStatusBloc] 收到重置事件:清空状态 - 当前状态:${state.runtimeType}',
|
||||
@@ -601,10 +695,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
|
||||
// 🔥 关键:无论缓存是否有效,都必须 emit 触发 BlocBuilder 重建
|
||||
if (!isClosed) {
|
||||
emit(DeviceStatusUpdated(
|
||||
_cachedStatus ?? RunningStatusEntity(),
|
||||
_cachedGps ?? GPSEntity(0.0, 0.0),
|
||||
));
|
||||
emit(
|
||||
DeviceStatusUpdated(
|
||||
_cachedStatus ?? RunningStatusEntity(),
|
||||
_cachedGps ?? GPSEntity(0.0, 0.0),
|
||||
),
|
||||
);
|
||||
debugPrint('📤 [DeviceStatusBloc] 已 emit 停止信号,触发 UI 更新');
|
||||
}
|
||||
|
||||
@@ -642,6 +738,7 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
// 🔥 重置设备ID
|
||||
_currentDeviceId = null;
|
||||
_currentListeningSn = null;
|
||||
emergencyStopReading = null;
|
||||
|
||||
return Future.value();
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remot
|
||||
/// 由调用方决定注入哪一个实现,UI 与控制语义代码零改动。
|
||||
///
|
||||
/// 段位值统一沿用远程遥控编码:上=1、中=0、下=2
|
||||
/// (割刀 1 抬 / 2 降、底盘 1 升 / 2 降、点火 1 点火 / 2 熄火,0 都是停止)。
|
||||
/// 割刀段位由 Cubit 映射为开1/关0/不操作2;底盘、点火编码不变。
|
||||
abstract interface class PvRobotCommandChannel {
|
||||
/// 前进 / 后退(左摇杆,-100~100,上推为正=前进)。
|
||||
void sendDriveY(int y);
|
||||
@@ -19,19 +19,19 @@ abstract interface class PvRobotCommandChannel {
|
||||
/// 底盘升降。
|
||||
void sendChassis(int cmd);
|
||||
|
||||
/// 割刀升降。
|
||||
/// 割刀滑块段位:1=上拨开启、2=下拨关闭、0=回中不操作。
|
||||
void sendMower(int cmd);
|
||||
|
||||
/// 点火 / 熄火。
|
||||
void sendIgnition(int cmd);
|
||||
|
||||
/// 紧急停止。
|
||||
void sendEmergencyStop(bool on);
|
||||
Future<bool> sendEmergencyStop(bool on);
|
||||
|
||||
/// 双轴归零(松手即停,安全底线)。
|
||||
Future<void> stopAllMovement();
|
||||
|
||||
/// 进入控制态:查询一次控制权限,并开始持续下发控制帧(默认 100ms 控制循环)。
|
||||
/// 进入控制态:查询一次控制权限,并开始持续下发控制帧(默认 250ms 控制循环)。
|
||||
void activate();
|
||||
|
||||
/// 退出控制态:归零、停止控制循环、释放控制权、复位权限。
|
||||
@@ -58,22 +58,22 @@ class RemoteControlRobotChannel implements PvRobotCommandChannel {
|
||||
void sendChassis(int cmd) => _cubit.sendChassisCommand(cmd);
|
||||
|
||||
@override
|
||||
void sendMower(int cmd) => _cubit.sendMowerCommand(cmd);
|
||||
void sendMower(int cmd) => _cubit.sendMowerSliderCommand(cmd);
|
||||
|
||||
@override
|
||||
void sendIgnition(int cmd) => _cubit.sendFireCommand(cmd);
|
||||
|
||||
@override
|
||||
void sendEmergencyStop(bool on) => _cubit.updateEmergency(on);
|
||||
Future<bool> sendEmergencyStop(bool on) => _cubit.updateEmergency(on);
|
||||
|
||||
@override
|
||||
Future<void> stopAllMovement() => _cubit.stopAllMovement();
|
||||
Future<void> stopAllMovement() => _cubit.stopAllMovement(reason: 'hud_stop');
|
||||
|
||||
@override
|
||||
void activate() {
|
||||
final cubit = _cubit;
|
||||
// 与远程遥控页一致:进控制态先「仅查询」一次控制权限(grabControl=false,
|
||||
// 只把接口结果如实同步到 hasPermission,不发 TCP 抢占),再启动 100ms 控制循环。
|
||||
// 只把接口结果如实同步到 hasPermission,不发 TCP 抢占),再启动 250ms 控制循环。
|
||||
// 无权限时控制循环会自动跳过发送,行为与极简模式完全相同。
|
||||
final deviceName = cubit.state.targetDevice?.deviceName;
|
||||
if (deviceName != null && deviceName.isNotEmpty) {
|
||||
@@ -90,11 +90,11 @@ class RemoteControlRobotChannel implements PvRobotCommandChannel {
|
||||
|
||||
@override
|
||||
Future<bool?> deactivate() async {
|
||||
// 先解除急停,避免 HUD 退出时残留 isEmergency=true,
|
||||
// 让下一次进入(含极简远程遥控页)控制循环被锁住无法运动。
|
||||
_cubit.updateEmergency(false);
|
||||
_cubit.cancelPermissionRequest();
|
||||
// 退出页面不再自动解除急停;只有明确的用户操作可发送 eStop=0。
|
||||
// 旧调用保留:_cubit.updateEmergency(false);
|
||||
// 停止指令无视权限强制发送,先归零再停循环,避免残留运动。
|
||||
await _cubit.stopAllMovement();
|
||||
await _cubit.stopAllMovement(reason: 'hud_deactivate');
|
||||
_cubit.stopControlLoop();
|
||||
// 与远程遥控页一致:退出释放远程控制权限(type=2),设备名取当前 targetDevice。
|
||||
final deviceId = _cubit.state.targetDevice?.deviceName;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../../devices/domain/entities/running_status_entity.dart';
|
||||
|
||||
/// 光伏巡检机器人实时遥测数据(本批次为 Mock 假数据,后续可替换为 MQTT/TCP 真实来源)
|
||||
/// 光伏巡检机器人遥测数据;状态值缺失时保留 null,由 UI 展示未知。
|
||||
///
|
||||
/// 采用不可变对象 + copyWith,便于后续接入真实数据流时局部更新字段。
|
||||
@immutable
|
||||
@@ -15,7 +16,14 @@ class PvTelemetry {
|
||||
this.isAutoDriving = true,
|
||||
// 默认留空:具体文案由 UI 层按当前语言兜底(见 PvInfoColumn)
|
||||
this.taskStatus = '',
|
||||
this.speed = 0.3,
|
||||
this.speed,
|
||||
this.leftMeasuredRpm,
|
||||
this.rightMeasuredRpm,
|
||||
this.leftTargetRpm,
|
||||
this.rightTargetRpm,
|
||||
this.mowerRpm,
|
||||
this.motion,
|
||||
this.emergencyStop,
|
||||
this.mileage,
|
||||
this.networkNormal = true,
|
||||
this.temperature,
|
||||
@@ -39,8 +47,58 @@ class PvTelemetry {
|
||||
final bool isAutoDriving;
|
||||
final String taskStatus;
|
||||
|
||||
/// 当前速度 m/s
|
||||
final double speed;
|
||||
/// 当前线速度 m/s;负数表示倒车,null 表示未有效上报。
|
||||
final double? speed;
|
||||
final double? leftMeasuredRpm;
|
||||
final double? rightMeasuredRpm;
|
||||
final double? leftTargetRpm;
|
||||
final double? rightTargetRpm;
|
||||
|
||||
/// 车辆实时 cuttingSpeed / TCP 割刀转速;不使用本地启停指令推断。
|
||||
final double? mowerRpm;
|
||||
final String? motion;
|
||||
final bool? emergencyStop;
|
||||
|
||||
/// 每次从当前状态生成新快照,缺失字段不会沿用上帧数值或默认零值。
|
||||
factory PvTelemetry.fromRunningStatus(
|
||||
RunningStatusEntity? status, {
|
||||
String deviceName = '',
|
||||
bool obstacleAlert = false,
|
||||
}) {
|
||||
final raw = status?.hostRealtime?.rawData ?? const <String, dynamic>{};
|
||||
double? number(String field) {
|
||||
final value = raw[field];
|
||||
final parsed = value is num
|
||||
? value.toDouble()
|
||||
: double.tryParse(value?.toString() ?? '');
|
||||
return parsed != null && parsed.isFinite ? parsed : null;
|
||||
}
|
||||
|
||||
final cutter = double.tryParse(status?.knifeCuttingSpeed ?? '');
|
||||
final battery = number('battery_percentage');
|
||||
return PvTelemetry(
|
||||
deviceName: deviceName,
|
||||
obstacleAlert: obstacleAlert,
|
||||
battery: battery != null && battery >= 0 && battery <= 100
|
||||
? battery
|
||||
: null,
|
||||
mileage: number('total_work_distance'),
|
||||
temperature: number('main_temperature'),
|
||||
speed: number('linear_speed'),
|
||||
leftMeasuredRpm: number('left_measured_rpm'),
|
||||
rightMeasuredRpm: number('right_measured_rpm'),
|
||||
leftTargetRpm: number('left_target_rpm'),
|
||||
rightTargetRpm: number('right_target_rpm'),
|
||||
mowerRpm: cutter != null && cutter.isFinite ? cutter : null,
|
||||
motion: status?.hostRealtime?.motion,
|
||||
emergencyStop: status?.emergencyStop,
|
||||
controlMode: status?.controlMode,
|
||||
fixStatus: status?.qual,
|
||||
satelliteCount: status != null && status.satelliteCnt > 0
|
||||
? status.satelliteCnt
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// 巡检里程(累计作业里程);null=未收到实时数据(显示"未知")
|
||||
final double? mileage;
|
||||
@@ -79,6 +137,13 @@ class PvTelemetry {
|
||||
bool? isAutoDriving,
|
||||
String? taskStatus,
|
||||
double? speed,
|
||||
double? leftMeasuredRpm,
|
||||
double? rightMeasuredRpm,
|
||||
double? leftTargetRpm,
|
||||
double? rightTargetRpm,
|
||||
double? mowerRpm,
|
||||
String? motion,
|
||||
bool? emergencyStop,
|
||||
double? mileage,
|
||||
bool? networkNormal,
|
||||
double? temperature,
|
||||
@@ -98,6 +163,13 @@ class PvTelemetry {
|
||||
isAutoDriving: isAutoDriving ?? this.isAutoDriving,
|
||||
taskStatus: taskStatus ?? this.taskStatus,
|
||||
speed: speed ?? this.speed,
|
||||
leftMeasuredRpm: leftMeasuredRpm ?? this.leftMeasuredRpm,
|
||||
rightMeasuredRpm: rightMeasuredRpm ?? this.rightMeasuredRpm,
|
||||
leftTargetRpm: leftTargetRpm ?? this.leftTargetRpm,
|
||||
rightTargetRpm: rightTargetRpm ?? this.rightTargetRpm,
|
||||
mowerRpm: mowerRpm ?? this.mowerRpm,
|
||||
motion: motion ?? this.motion,
|
||||
emergencyStop: emergencyStop ?? this.emergencyStop,
|
||||
mileage: mileage ?? this.mileage,
|
||||
networkNormal: networkNormal ?? this.networkNormal,
|
||||
temperature: temperature ?? this.temperature,
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import 'dart:async';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/device_control_mode.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/mode_independent_control.dart';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../remote_control/presentation/widgets/emergency_stop_confirmation.dart';
|
||||
import '../../../remote_control/presentation/widgets/emergency_stop_button.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -12,13 +15,14 @@ import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
import 'package:maibu_satabot_v2/core/env/env_config.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/remote_control_link_feedback.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/local_camera/presentation/cubit/local_camera_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/usb_camera/data/uvc_camera_service.dart';
|
||||
@@ -75,7 +79,6 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
final GlobalKey _videoKey = GlobalKey();
|
||||
|
||||
/// 本批次使用 Mock 遥测数据
|
||||
final PvTelemetry _telemetry = const PvTelemetry();
|
||||
|
||||
/// 遥控指令传输通道:当前为 TCP 实现(委托 `RemoteControlCubit`),
|
||||
/// 以后接蓝牙 / 下位机只换一个实现类,HUD 与本页面代码零改动。
|
||||
@@ -89,13 +92,11 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
/// 尾部那次 stopControlLoop() 会把刚起来的循环又关掉,HUD 就变成
|
||||
/// “摇杆推了没反应”。故延后到 deactivate 收尾再起循环。
|
||||
bool _deactivating = false;
|
||||
bool _emergencyConfirming = false;
|
||||
|
||||
/// deactivate 期间收到过重新进入控制态的请求。
|
||||
bool _restartAfterDeactivate = false;
|
||||
|
||||
/// 急停开关态:HUD 急停钮每点一次翻转,经通道下发 updateEmergency。
|
||||
bool _emergencyOn = false;
|
||||
|
||||
/// 远程控制单例(HUD 与原远程遥控页共用它,指令通道内部也委托它)。
|
||||
RemoteControlCubit get _cubit => sl<RemoteControlCubit>();
|
||||
|
||||
@@ -147,41 +148,12 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
: AppLocalizations.of(context).translate('pv_control.no_device');
|
||||
}
|
||||
|
||||
/// 实际下发的遥测:真实字段来自全局 [DeviceStatusBloc] 的 host 实时数据
|
||||
/// (电量/巡检里程/设备温度),未收到时置 null 由 UI 显示"未知";
|
||||
/// 开启「模拟障碍物信息」相当于收到机器告警推送,叠加 obstacleAlert。
|
||||
/// 使用当前设备的实时快照;未上报的字段由 UI 显示未知。
|
||||
PvTelemetry _resolveTelemetry(DeviceStatusState dsState, String deviceName) {
|
||||
double? battery;
|
||||
double? mileage;
|
||||
double? temp;
|
||||
int? fixStatus;
|
||||
int? satelliteCount;
|
||||
String? controlMode;
|
||||
if (dsState is DeviceStatusUpdated) {
|
||||
final s = dsState.status;
|
||||
// 定位质量:来自 location/post 的 fix_status(qual)
|
||||
fixStatus = s.qual;
|
||||
// 控制模式:与“设备数据监控”同一口径,只要收到状态就跟随,不加 host 门控
|
||||
controlMode = s.controlMode;
|
||||
// 卫星数:realtime/post 尚未推送,无数据源时保持 null 显示"未知"
|
||||
if (s.satelliteCnt > 0) satelliteCount = s.satelliteCnt;
|
||||
// 以下三项来自 host 实时话题(device/{sn}/host/realTime/message)
|
||||
if (s.hostDataReceived) {
|
||||
battery = double.tryParse(s.battery);
|
||||
mileage = s.totalWorkDistance;
|
||||
temp = s.chipTemp;
|
||||
}
|
||||
}
|
||||
return _telemetry.copyWith(
|
||||
// 设备名用真实选中的设备,不再用 PvTelemetry 里写死的占位名
|
||||
return PvTelemetry.fromRunningStatus(
|
||||
dsState is DeviceStatusUpdated ? dsState.status : null,
|
||||
deviceName: deviceName,
|
||||
obstacleAlert: _simObstacle,
|
||||
battery: battery,
|
||||
mileage: mileage,
|
||||
temperature: temp,
|
||||
fixStatus: fixStatus,
|
||||
satelliteCount: satelliteCount,
|
||||
controlMode: controlMode,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -230,7 +202,7 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
if (widget.deviceId.isNotEmpty && token != null) {
|
||||
setState(() {
|
||||
_streamUrl =
|
||||
'webrtc://${TCPConsts.TCP_IP}/live/livestream/${widget.deviceId}?token=$token';
|
||||
'webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/${widget.deviceId}?token=$token';
|
||||
});
|
||||
} else {
|
||||
debugPrint('❌ [PvControl] 视频URL初始化失败:deviceId 或 token 为空');
|
||||
@@ -310,15 +282,43 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
);
|
||||
}
|
||||
|
||||
void _onEmergencyStop() {
|
||||
// HUD 急停钮为“点一下急停 / 再点一下恢复”的切换态(按钮自身不携带 on/off)。
|
||||
_emergencyOn = !_emergencyOn;
|
||||
_channel.sendEmergencyStop(_emergencyOn);
|
||||
Future<void> _onEmergencyStop() async {
|
||||
if (_emergencyConfirming || _cubit.state.isEmergencyRequestPending) return;
|
||||
final sn = _cubit.state.targetDevice?.deviceName;
|
||||
final on = !_cubit.state.isEmergency;
|
||||
if (!_cubit.checkEmergencyRequest(on)) {
|
||||
CapsuleToast.show(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.${_cubit.state.emergencyFeedbackKey}'),
|
||||
showCheck: false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_cubit.checkEmergencyRequest(on)) {
|
||||
CapsuleToast.show(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.${_cubit.state.emergencyFeedbackKey}'),
|
||||
showCheck: false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
_emergencyConfirming = true;
|
||||
bool confirmed;
|
||||
try {
|
||||
confirmed = await confirmEmergencyStop(context, engage: on, sn: sn ?? '');
|
||||
} finally {
|
||||
_emergencyConfirming = false;
|
||||
}
|
||||
if (!confirmed || !mounted || sn != _cubit.state.targetDevice?.deviceName) {
|
||||
return;
|
||||
}
|
||||
await _channel.sendEmergencyStop(on);
|
||||
if (!mounted || sn != _cubit.state.targetDevice?.deviceName) return;
|
||||
final tr = AppLocalizations.of(context);
|
||||
CapsuleToast.show(
|
||||
_emergencyOn
|
||||
? tr.translate('pv_control.toast_emergency_sent')
|
||||
: tr.translate('pv_control.toast_emergency_released'),
|
||||
tr.translate('remote_control.${_cubit.state.emergencyFeedbackKey}'),
|
||||
showCheck: false,
|
||||
);
|
||||
}
|
||||
@@ -338,8 +338,7 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
return;
|
||||
}
|
||||
_controlActive = true;
|
||||
// deactivate 会清除急停态,重新进入从“未急停”开始,与通道保持同步。
|
||||
_emergencyOn = false;
|
||||
// 急停由共享 Cubit 保持,重新进入页面不自动解除。
|
||||
_channel.activate();
|
||||
}
|
||||
|
||||
@@ -679,6 +678,7 @@ class _PvControlPageState extends State<PvControlPage> {
|
||||
deviceName: widget.deviceName,
|
||||
target: ControlModeTarget.remote,
|
||||
cancelToPreview: true,
|
||||
emergencyStopControl: const EmergencyStopButton(),
|
||||
onReady: _startControl,
|
||||
child: _buildPage(context),
|
||||
);
|
||||
@@ -863,15 +863,20 @@ class _PvTopNav extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: onSettings,
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
|
||||
icon: const Icon(
|
||||
Icons.settings,
|
||||
color: PvColors.textSecondary,
|
||||
size: 20,
|
||||
RemoteControlHeartbeatIndicator(
|
||||
heartbeats: sl<RemoteControlCubit>().serverHeartbeats,
|
||||
),
|
||||
ModeIndependentControl(
|
||||
child: IconButton(
|
||||
onPressed: onSettings,
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
|
||||
icon: const Icon(
|
||||
Icons.settings,
|
||||
color: PvColors.textSecondary,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import '../../../remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import '../../../device_control_mode/presentation/widgets/mode_independent_control.dart';
|
||||
|
||||
import '../theme/pv_colors.dart';
|
||||
|
||||
@@ -48,9 +51,7 @@ class PvControlBar extends StatelessWidget {
|
||||
onTap: onPauseTask,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: PvEmergencyStopButton(onTap: onEmergencyStop),
|
||||
),
|
||||
Expanded(child: PvEmergencyStopButton(onTap: onEmergencyStop)),
|
||||
Expanded(
|
||||
child: _ControlButton(
|
||||
icon: Icons.videocam,
|
||||
@@ -160,9 +161,9 @@ class _PvEmergencyStopButtonState extends State<PvEmergencyStopButton>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller;
|
||||
|
||||
/// 是否处于「急停中」:默认 false(正常态、不呼吸)。
|
||||
/// 点击一次进入急停(呼吸 + 「急停中」提示),再点一次解除恢复正常。
|
||||
bool _active = false;
|
||||
bool get _active =>
|
||||
context.read<RemoteControlCubit>().state.isEmergency &&
|
||||
context.read<RemoteControlCubit>().state.hasEmergencyStatus;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -179,19 +180,30 @@ class _PvEmergencyStopButtonState extends State<PvEmergencyStopButton>
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _handleTap() {
|
||||
setState(() => _active = !_active);
|
||||
if (_active) {
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
final state = context.watch<RemoteControlCubit>().state;
|
||||
final active = state.isEmergency && state.hasEmergencyStatus;
|
||||
if (active && !_controller.isAnimating) {
|
||||
_controller.repeat(reverse: true);
|
||||
} else {
|
||||
} else if (!active && _controller.isAnimating) {
|
||||
_controller.stop();
|
||||
_controller.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleTap() {
|
||||
if (context.read<RemoteControlCubit>().state.isEmergencyRequestPending)
|
||||
return;
|
||||
widget.onTap();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context) =>
|
||||
ModeIndependentControl(child: _buildButton(context));
|
||||
|
||||
Widget _buildButton(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, child) {
|
||||
@@ -214,7 +226,9 @@ class _PvEmergencyStopButtonState extends State<PvEmergencyStopButton>
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: PvColors.danger.withValues(alpha: 0.5 + 0.35 * t),
|
||||
color: PvColors.danger.withValues(
|
||||
alpha: 0.5 + 0.35 * t,
|
||||
),
|
||||
blurRadius: 18 + 12 * t,
|
||||
spreadRadius: 2 + 3 * t,
|
||||
),
|
||||
@@ -232,9 +246,11 @@ class _PvEmergencyStopButtonState extends State<PvEmergencyStopButton>
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text(
|
||||
AppLocalizations.of(context).translate(
|
||||
_active
|
||||
? 'pv_control.emergency_stopping'
|
||||
: 'pv_control.emergency_stop',
|
||||
!context.read<RemoteControlCubit>().state.hasEmergencyStatus
|
||||
? 'remote_control.emergency_unknown'
|
||||
: _active
|
||||
? 'remote_control.emergency_stopping'
|
||||
: 'remote_control.emergency_inactive',
|
||||
),
|
||||
maxLines: 1,
|
||||
textAlign: TextAlign.center,
|
||||
|
||||
@@ -38,8 +38,9 @@ class PvInfoColumn extends StatelessWidget {
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
).translate('pv_control.current_speed'),
|
||||
value: telemetry.speed.toStringAsFixed(1),
|
||||
unit: 'm/s',
|
||||
value: telemetry.speed?.toStringAsFixed(2) ??
|
||||
AppLocalizations.of(context).translate('pv_control.unknown'),
|
||||
unit: telemetry.speed == null ? '' : 'm/s',
|
||||
)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: _MetricCard.icon(
|
||||
|
||||
@@ -3,12 +3,14 @@ import 'dart:math' as math;
|
||||
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/mode_independent_control.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/components/control_mode_text.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/entities/reverse_camera_data.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
@@ -22,6 +24,8 @@ import '../models/pv_video_source.dart';
|
||||
import '../theme/pv_colors.dart';
|
||||
import '../theme/pv_hud_theme.dart';
|
||||
import '../channel/pv_robot_command_channel.dart';
|
||||
import '../../../remote_control/presentation/widgets/remote_control_link_feedback.dart';
|
||||
import '../../../remote_control/presentation/widgets/permission_request_feedback.dart';
|
||||
import 'pv_control_bar.dart';
|
||||
import 'pv_rear_view_card.dart';
|
||||
import 'pv_local_rtsp_video.dart';
|
||||
@@ -53,7 +57,7 @@ typedef _PvSheetSpec = ({
|
||||
/// 计算缩放系数 [_sc],手机横屏(高约 360 → _sc≈0.64)时顶栏占比、字号、按钮
|
||||
/// 全部等比缩小,平板(高约 600 → _sc≈1.07)时放大,从而在两种设备上还原版式。
|
||||
///
|
||||
/// AR 障碍框、遥测数值为写死的假数据;控制指令(摇杆 / 割刀 / 底盘 / 点火 / 急停)
|
||||
/// 状态卡由实时遥测驱动;控制指令(摇杆 / 割刀 / 底盘 / 点火 / 急停)
|
||||
/// 已通过 [PvRobotCommandChannel] 接入(TCP 实现委托远程遥控 Cubit,见 pv_robot_command_channel.dart)。
|
||||
class PvManualControlView extends StatefulWidget {
|
||||
const PvManualControlView({
|
||||
@@ -615,6 +619,10 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
SizedBox(width: d(8)),
|
||||
// 「正在控制 / 未在控制」状态胶囊(与远程遥控顶栏同款、同逻辑)
|
||||
_buildControlStatusChip(),
|
||||
RemoteControlHeartbeatIndicator(
|
||||
heartbeats: sl<RemoteControlCubit>().serverHeartbeats,
|
||||
size: d(9),
|
||||
),
|
||||
// 中:链路信息(FittedBox 保证窄屏自动缩小不溢出)
|
||||
Expanded(
|
||||
child: Padding(
|
||||
@@ -686,10 +694,12 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
active: _showSidePips,
|
||||
onTap: _toggleSidePips,
|
||||
),
|
||||
_navItem(
|
||||
Icons.settings_outlined,
|
||||
tr.translate('pv_control.nav_settings'),
|
||||
onTap: widget.onSettings,
|
||||
ModeIndependentControl(
|
||||
child: _navItem(
|
||||
Icons.settings_outlined,
|
||||
tr.translate('pv_control.nav_settings'),
|
||||
onTap: widget.onSettings,
|
||||
),
|
||||
),
|
||||
SizedBox(width: d(4)),
|
||||
],
|
||||
@@ -752,17 +762,18 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
initialData: cubit.state,
|
||||
stream: cubit.stream,
|
||||
builder: (context, snapshot) {
|
||||
final hasPermission = snapshot.data?.hasPermission ?? false;
|
||||
final tr = AppLocalizations.of(context);
|
||||
final color = hasPermission
|
||||
? PvHudColors.success
|
||||
: PvHudColors.danger;
|
||||
final permissionState = snapshot.data ?? cubit.state;
|
||||
final hasPermission = permissionState.hasPermission;
|
||||
final busy = permissionState.isPermissionRequestBusy;
|
||||
final color = busy
|
||||
? Colors.orange
|
||||
: hasPermission ? PvHudColors.success : PvHudColors.danger;
|
||||
final chip = Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(3)),
|
||||
decoration: BoxDecoration(
|
||||
color: hasPermission
|
||||
? PvHudColors.successBg
|
||||
: PvHudColors.dangerBg,
|
||||
color: busy
|
||||
? Colors.orange.withValues(alpha: 0.12)
|
||||
: hasPermission ? PvHudColors.successBg : PvHudColors.dangerBg,
|
||||
borderRadius: BorderRadius.circular(d(20)),
|
||||
),
|
||||
child: Row(
|
||||
@@ -775,9 +786,7 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
),
|
||||
SizedBox(width: d(4)),
|
||||
Text(
|
||||
hasPermission
|
||||
? tr.translate('remote_control.controlling')
|
||||
: tr.translate('remote_control.not_controlling'),
|
||||
permissionStatusText(context, permissionState),
|
||||
maxLines: 1,
|
||||
style: s(PvHudType.caption, 11).copyWith(
|
||||
color: color,
|
||||
@@ -787,19 +796,16 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
],
|
||||
),
|
||||
);
|
||||
return GestureDetector(
|
||||
return PermissionRequestFeedback(
|
||||
cubit: cubit,
|
||||
child: Tooltip(
|
||||
message: permissionStatusHint(context, permissionState),
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () {
|
||||
// 已在控制:无需重复抢占。
|
||||
if (hasPermission) return;
|
||||
final targetDevice = cubit.state.targetDevice;
|
||||
if (targetDevice == null) {
|
||||
debugPrint('❌ [PV遥控] targetDevice 为空,无法请求权限');
|
||||
return;
|
||||
}
|
||||
debugPrint('🔑 [PV遥控] 👆 点击“未在控制”,请求抢占控制权');
|
||||
if (hasPermission || busy) return;
|
||||
cubit.requestControlPermissionS(
|
||||
targetDevice.deviceName,
|
||||
cubit.state.targetDevice?.deviceName ?? '',
|
||||
'app',
|
||||
source: '手动点击',
|
||||
grabControl: true,
|
||||
@@ -816,6 +822,8 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
),
|
||||
child: chip,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1348,12 +1356,26 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
);
|
||||
}
|
||||
|
||||
/// 状态卡:图标 + 标签 + 数值的竖排列表(设计稿左栏第二张卡)。
|
||||
Widget _statusCard() {
|
||||
final tr = AppLocalizations.of(context);
|
||||
final telemetry = widget.telemetry;
|
||||
final unknown = tr.translate('pv_control.unknown');
|
||||
String speedText(double? value, String unit) =>
|
||||
value == null ? unknown : '${value.toStringAsFixed(2)} $unit';
|
||||
final motionKey = telemetry.emergencyStop == true
|
||||
? 'pv_control.emergency_stopping'
|
||||
: switch (telemetry.motion) {
|
||||
'moving' => 'pv_control.status_moving',
|
||||
'stopped' => 'pv_control.status_stopped',
|
||||
'blocked' => 'pv_control.status_blocked',
|
||||
_ => 'pv_control.unknown',
|
||||
};
|
||||
final motionDanger = telemetry.emergencyStop == true ||
|
||||
telemetry.motion == 'blocked';
|
||||
final mowerRunning = telemetry.mowerRpm != null && telemetry.mowerRpm != 0;
|
||||
final batteryText = widget.telemetry.battery == null
|
||||
? tr.translate('pv_control.unknown')
|
||||
: '${widget.telemetry.battery!.toStringAsFixed(0)}% (5.6 h)';
|
||||
? unknown
|
||||
: '${widget.telemetry.battery!.toStringAsFixed(0)}%';
|
||||
final fixQuality = widget.telemetry.fixStatus == 4;
|
||||
return _panel(
|
||||
padding: EdgeInsets.symmetric(horizontal: d(10), vertical: d(6)),
|
||||
@@ -1362,30 +1384,59 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
_statusRow(
|
||||
Icons.directions_car_filled_outlined,
|
||||
tr.translate('pv_control.vehicle_status'),
|
||||
tr.translate('pv_control.status_normal'),
|
||||
valueColor: PvHudColors.success,
|
||||
capsule: true,
|
||||
tr.translate(motionKey),
|
||||
valueColor: motionDanger
|
||||
? PvHudColors.danger
|
||||
: motionKey == 'pv_control.unknown'
|
||||
? PvHudColors.textSecondary
|
||||
: PvHudColors.success,
|
||||
),
|
||||
_statusRow(
|
||||
Icons.speed,
|
||||
tr.translate('pv_control.drive_speed'),
|
||||
'1.2 m/s',
|
||||
speedText(telemetry.speed, 'm/s'),
|
||||
),
|
||||
_statusRow(
|
||||
Icons.speed,
|
||||
tr.translate('pv_control.left_measured_rpm'),
|
||||
speedText(telemetry.leftMeasuredRpm, 'rpm'),
|
||||
),
|
||||
_statusRow(
|
||||
Icons.speed,
|
||||
tr.translate('pv_control.right_measured_rpm'),
|
||||
speedText(telemetry.rightMeasuredRpm, 'rpm'),
|
||||
),
|
||||
_statusRow(
|
||||
Icons.speed,
|
||||
tr.translate('pv_control.left_target_rpm'),
|
||||
speedText(telemetry.leftTargetRpm, 'rpm'),
|
||||
),
|
||||
_statusRow(
|
||||
Icons.speed,
|
||||
tr.translate('pv_control.right_target_rpm'),
|
||||
speedText(telemetry.rightTargetRpm, 'rpm'),
|
||||
),
|
||||
_statusRow(
|
||||
Icons.settings_outlined,
|
||||
tr.translate('pv_control.gear'),
|
||||
tr.translate('pv_control.gear_low'),
|
||||
unknown,
|
||||
),
|
||||
_statusRow(
|
||||
Icons.content_cut,
|
||||
tr.translate('pv_control.mower_status'),
|
||||
tr.translate('pv_control.mower_running'),
|
||||
valueColor: PvHudColors.success,
|
||||
telemetry.mowerRpm == null
|
||||
? unknown
|
||||
: tr.translate(mowerRunning
|
||||
? 'pv_control.mower_running'
|
||||
: 'pv_control.mower_stopped'),
|
||||
valueColor: mowerRunning
|
||||
? PvHudColors.success
|
||||
: PvHudColors.textSecondary,
|
||||
),
|
||||
_statusRow(
|
||||
Icons.height,
|
||||
tr.translate('pv_control.chassis_height'),
|
||||
'120 mm',
|
||||
unknown,
|
||||
),
|
||||
_statusRow(
|
||||
Icons.battery_5_bar,
|
||||
@@ -1684,7 +1735,9 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
child: CCJoystick(
|
||||
radius: radius,
|
||||
axisHint: AxisHint.forwardBackward,
|
||||
onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields),
|
||||
skin: _joystickSkin(),
|
||||
onPress: () => RemoteControlLinkNotice.showIfDisconnected(context),
|
||||
onValueChanged: (v) {
|
||||
final int y = v.y.toInt();
|
||||
if (y == _lastDriveY) return;
|
||||
@@ -1705,7 +1758,9 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
child: CCJoystick(
|
||||
radius: radius,
|
||||
axisHint: AxisHint.leftRight,
|
||||
onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields),
|
||||
skin: _joystickSkin(),
|
||||
onPress: () => RemoteControlLinkNotice.showIfDisconnected(context),
|
||||
onValueChanged: (v) {
|
||||
final int x = v.x.toInt().abs() < 1 ? 0 : v.x.toInt();
|
||||
if (x == _lastDriveX) return;
|
||||
@@ -1931,7 +1986,7 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
mid: 'assets/svgs/remote_scissors.svg',
|
||||
down: 'assets/svgs/remote_down.svg',
|
||||
segUp: 'pv_control.seg_mower_up',
|
||||
segMid: 'pv_control.seg_stop',
|
||||
segMid: 'pv_control.seg_mower_idle',
|
||||
segDown: 'pv_control.seg_mower_down',
|
||||
turns: 0,
|
||||
),
|
||||
@@ -2065,6 +2120,7 @@ class _PvManualControlViewState extends State<PvManualControlView>
|
||||
/// 长按起手:给一下中等强度震动做确认(手指按在按钮上就触发了,无反馈很
|
||||
/// 容易被当成没响应),并亮气泡、从中位(停)开始。
|
||||
void _onScrubStart(String sheetKey) {
|
||||
RemoteControlLinkNotice.showIfDisconnected(context);
|
||||
_sheetCloseTimer?.cancel();
|
||||
_sheetCloseTimer = null;
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
@@ -4,18 +4,19 @@ import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../../core/logging/control_permission_diagnostics.dart';
|
||||
import '../../../../core/storage/user_storage.dart';
|
||||
import '../../domain/entities/control_permission_failure.dart';
|
||||
|
||||
class RemoteHttpDatasource {
|
||||
final Dio _dio;
|
||||
final UserStorage _userStorage; // 🔥 新增字段
|
||||
final ILoggerService _logger = GetIt.I<ILoggerService>();
|
||||
|
||||
|
||||
RemoteHttpDatasource(this._dio, this._userStorage);
|
||||
RemoteHttpDatasource(this._dio, this._userStorage);
|
||||
|
||||
/// 示例:获取控制授权 (对应之前逻辑中的权限申请)
|
||||
/* Future<Map<String, dynamic>> requestControlAuth(String robotId) async {
|
||||
/* Future<Map<String, dynamic>> requestControlAuth(String robotId) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'/robot/auth/request',
|
||||
@@ -27,71 +28,92 @@ class RemoteHttpDatasource {
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
/// 🔥 返回完整权限信息: {hasPermission, owner}
|
||||
Future<Map<String, dynamic>> requestRemoteControlViaHttp(String deviceName, String platform) async {
|
||||
final logPrefix = '🔑 [RemoteHttp][获取权限接口]';
|
||||
final user = await _userStorage.getUser();
|
||||
if (user == null) {
|
||||
debugPrint('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限');
|
||||
_logger.logWithLevel('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限', shouldLog: true);
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
}
|
||||
final token = user.token;
|
||||
|
||||
debugPrint('$logPrefix 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform');
|
||||
_logger.logWithLevel(
|
||||
'$logPrefix 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
/// Queries the existing endpoint. Unknown/error responses are not "no permission".
|
||||
Future<Map<String, dynamic>> requestRemoteControlViaHttp(
|
||||
String deviceName,
|
||||
String platform,
|
||||
) async {
|
||||
final clock = Stopwatch()..start();
|
||||
try {
|
||||
final requestData = {'deviceId': deviceName, 'platform': platform};
|
||||
debugPrint('$logPrefix 请求地址: POST /forward/device/remoteControl');
|
||||
debugPrint('$logPrefix 实际请求体: $requestData');
|
||||
_logger.logWithLevel(
|
||||
'$logPrefix 请求地址: POST /forward/device/remoteControl, 请求体: $requestData',
|
||||
shouldLog: true,
|
||||
);
|
||||
final response = await _dio.post(
|
||||
'/forward/device/remoteControl',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ${token}',
|
||||
},
|
||||
),
|
||||
data: requestData);
|
||||
|
||||
debugPrint("$logPrefix HTTP响应状态码: ${response.statusCode}");
|
||||
_logger.logWithLevel("$logPrefix HTTP响应状态码: ${response.statusCode}", shouldLog: true);
|
||||
|
||||
final responseData = response.data as Map<String, dynamic>;
|
||||
debugPrint("$logPrefix 完整响应数据:$responseData");
|
||||
_logger.logWithLevel("$logPrefix 完整响应数据:$responseData", shouldLog: true);
|
||||
|
||||
// 🔥 关键:先获取响应的 data 字段,再获取 remoteControl 和 owner
|
||||
final dataField = responseData['data'] as Map<String, dynamic>?;
|
||||
if (dataField != null) {
|
||||
final bool hasRemoteControl = dataField['remoteControl'] as bool? ?? false;
|
||||
final String? owner = dataField['owner'] as String?;
|
||||
|
||||
debugPrint("$logPrefix 解析成功 - remoteControl=$hasRemoteControl, owner=$owner");
|
||||
_logger.logWithLevel(
|
||||
"$logPrefix 解析成功 - remoteControl=$hasRemoteControl, owner=$owner",
|
||||
shouldLog: true,
|
||||
);
|
||||
// 🔥 返回完整权限信息
|
||||
return {'hasPermission': hasRemoteControl, 'owner': owner};
|
||||
} else {
|
||||
debugPrint("$logPrefix 缺少 data 字段,响应结构异常");
|
||||
_logger.logWithLevel("$logPrefix 缺少 data 字段,响应结构异常", shouldLog: true);
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
final user = await _userStorage.getUser();
|
||||
if (user == null || user.token.trim().isEmpty) {
|
||||
throw ControlPermissionFailure('permission_auth_required');
|
||||
}
|
||||
ControlPermissionDiagnostics.event('HTTP请求', {
|
||||
'method': 'POST',
|
||||
'path': '/forward/device/remoteControl',
|
||||
'requestDevice': deviceName,
|
||||
'platform': platform,
|
||||
'authorizationPresent': true,
|
||||
});
|
||||
final response = await _dio.post(
|
||||
'/forward/device/remoteControl',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + user.token,
|
||||
},
|
||||
),
|
||||
data: {'deviceId': deviceName, 'platform': platform},
|
||||
);
|
||||
final body = response.data;
|
||||
final responseData = body is Map ? body['data'] : null;
|
||||
ControlPermissionDiagnostics.event('HTTP响应', {
|
||||
'httpStatus': response.statusCode,
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
'businessCode': ControlPermissionDiagnostics.scalar(
|
||||
body is Map ? body['code'] : null,
|
||||
),
|
||||
'dataType': responseData.runtimeType.toString(),
|
||||
'remoteControl': ControlPermissionDiagnostics.scalar(
|
||||
responseData is Map ? responseData['remoteControl'] : null,
|
||||
),
|
||||
'owner': ControlPermissionDiagnostics.scalar(
|
||||
responseData is Map ? responseData['owner'] : null,
|
||||
),
|
||||
'ownerFieldPresent':
|
||||
responseData is Map && responseData.containsKey('owner'),
|
||||
});
|
||||
if (body is! Map) {
|
||||
throw ControlPermissionFailure('permission_query_invalid');
|
||||
}
|
||||
final code = body['code'];
|
||||
if (code != null && code.toString() != '200') {
|
||||
throw ControlPermissionFailure(
|
||||
code.toString() == '401' || code.toString() == '403'
|
||||
? 'permission_auth_required'
|
||||
: 'permission_query_rejected',
|
||||
);
|
||||
}
|
||||
final data = body['data'];
|
||||
if (data is! Map ||
|
||||
data['remoteControl'] is! bool ||
|
||||
(data['owner'] != null && data['owner'] is! String)) {
|
||||
throw ControlPermissionFailure('permission_query_invalid');
|
||||
}
|
||||
return {'hasPermission': data['remoteControl'], 'owner': data['owner']};
|
||||
} on DioException catch (e) {
|
||||
ControlPermissionDiagnostics.event('HTTP网络异常', {
|
||||
'errorType': e.type.name,
|
||||
'httpStatus': e.response?.statusCode,
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
});
|
||||
if (e.response?.statusCode == 401 || e.response?.statusCode == 403) {
|
||||
throw ControlPermissionFailure('permission_auth_required');
|
||||
}
|
||||
if (e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.sendTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout) {
|
||||
throw ControlPermissionFailure('permission_query_timeout');
|
||||
}
|
||||
throw ControlPermissionFailure('permission_query_failed');
|
||||
} catch (e) {
|
||||
debugPrint('$logPrefix 请求远程控制权限失败:$e');
|
||||
_logger.logWithLevel('$logPrefix 请求远程控制权限失败:$e', level: 'ERROR', shouldLog: true);
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
ControlPermissionDiagnostics.event('HTTP业务异常', {
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'feedback': e is ControlPermissionFailure ? e.feedbackKey : null,
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
});
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,21 +138,23 @@ class RemoteHttpDatasource {
|
||||
debugPrint('📤 [RemoteHttp] releaseControl 实际请求体: $requestData');
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
HttpApiConsts.releaseControlUrl,
|
||||
options: Options(
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ${token}',
|
||||
},
|
||||
),
|
||||
data: requestData);
|
||||
HttpApiConsts.releaseControlUrl,
|
||||
options: Options(
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ${token}',
|
||||
},
|
||||
),
|
||||
data: requestData,
|
||||
);
|
||||
final responseData = response.data as Map<String, dynamic>;
|
||||
debugPrint('📋 [RemoteHttp] releaseControl 响应: $responseData');
|
||||
if (responseData['code'] == 200) {
|
||||
return true;
|
||||
}
|
||||
debugPrint(
|
||||
'⚠️ [RemoteHttp] releaseControl 返回 code=${responseData['code']},释放未成功');
|
||||
'⚠️ [RemoteHttp] releaseControl 返回 code=${responseData['code']},释放未成功',
|
||||
);
|
||||
return false;
|
||||
} catch (e) {
|
||||
debugPrint('❌ [RemoteHttp] releaseControl 请求失败:$e');
|
||||
@@ -138,5 +162,4 @@ class RemoteHttpDatasource {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import 'package:flutter/material.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../../core/logging/control_permission_diagnostics.dart';
|
||||
import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/protocol/machine_protocol_constants.dart';
|
||||
import '../../../../core/storage/user_storage.dart';
|
||||
import '../../domain/entities/control_permission_failure.dart';
|
||||
|
||||
/// 远程遥控 TCP 数据源
|
||||
/// 负责通过 TCP 协议发送控制指令和权限请求
|
||||
@@ -20,82 +22,68 @@ class RemoteTcpDatasource {
|
||||
|
||||
RemoteTcpDatasource(this._tcpClient, this._userStorage);
|
||||
|
||||
/// 发送 switch_control 权限请求(对应 Android 的 requestSwitchControl)
|
||||
///
|
||||
/// 这是获取设备控制权的第一步:
|
||||
/// 1. 先发送 TCP 0x12 指令携带 switch_control 请求
|
||||
/// 2. 等待服务端响应
|
||||
/// 3. 再调用 HTTP API 确认控制权
|
||||
Future<void> sendSwitchControlRequest(String deviceName) async {
|
||||
/// Sends the existing 0x12 request, with no protocol changes.
|
||||
Future<void> sendSwitchControlRequest(
|
||||
String deviceName, {
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
ControlPermissionDiagnostics.event('TCP申请检查', {
|
||||
'device': deviceName,
|
||||
'tcpConnected': _tcpClient.isConnected,
|
||||
});
|
||||
if (!_tcpClient.isConnected) {
|
||||
debugPrint('❌sendSwitchControlRequest [TCP] 无法发送权限请求:Socket 未连接');
|
||||
throw Exception('sendSwitchControlRequest TCP 未连接');
|
||||
throw ControlPermissionFailure('permission_tcp_disconnected');
|
||||
}
|
||||
|
||||
final user = await _userStorage.getUser();
|
||||
if (isCurrent != null && !isCurrent()) {
|
||||
ControlPermissionDiagnostics.event('TCP申请取消', {'reason': '获取用户信息后申请已失效'});
|
||||
return;
|
||||
}
|
||||
if (user == null || user.token.trim().isEmpty) {
|
||||
throw ControlPermissionFailure('permission_auth_required');
|
||||
}
|
||||
if (!_tcpClient.isConnected) {
|
||||
throw ControlPermissionFailure('permission_tcp_disconnected');
|
||||
}
|
||||
final request = {
|
||||
'request': 'switch_control',
|
||||
'deviceId': deviceName,
|
||||
'userId': user.username,
|
||||
'platform': 'app',
|
||||
'token': user.token,
|
||||
};
|
||||
final packet = buildSwitchControlPacket(utf8.encode(jsonEncode(request)));
|
||||
ControlPermissionDiagnostics.event('TCP申请构造完成', {
|
||||
'cmd': '0x12',
|
||||
'request': 'switch_control',
|
||||
'device': deviceName,
|
||||
'platform': 'app',
|
||||
'tokenPresent': user.token.isNotEmpty,
|
||||
'packetBytes': packet.length,
|
||||
});
|
||||
try {
|
||||
// 获取用户信息
|
||||
final user = await _userStorage.getUser();
|
||||
if (user == null || user.token == null) {
|
||||
debugPrint(
|
||||
'❌ sendSwitchControlRequest[TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包',
|
||||
);
|
||||
throw Exception('用户未登录或 Token 无效');
|
||||
}
|
||||
|
||||
final username = user.username;
|
||||
final token = user.token;
|
||||
final currentDeviceId = deviceName;
|
||||
|
||||
// 构造 JSON 请求体(参考 Android 代码)
|
||||
final request = {
|
||||
'request': 'switch_control',
|
||||
'deviceId': currentDeviceId,
|
||||
'userId': username,
|
||||
'platform': 'app',
|
||||
'token': token,
|
||||
};
|
||||
|
||||
final jsonStr = jsonEncode(request);
|
||||
final jsonBytes = utf8.encode(jsonStr);
|
||||
|
||||
debugPrint('sendSwitchControlRequest[TCP] 发送权限请求指令:$jsonStr');
|
||||
await _tcpClient
|
||||
.sendPermissionPacket(packet)
|
||||
.timeout(const Duration(seconds: 5));
|
||||
ControlPermissionDiagnostics.event('TCP申请本地完成', {
|
||||
'serverReceiptConfirmed': false,
|
||||
'note': '仅本地写入和flush完成,等待授权回包',
|
||||
});
|
||||
_logger.logWithLevel(
|
||||
'🔑 [TCP][获取权限] 发送权限请求指令:$jsonStr',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
// 使用 0x12 指令发送(cmdGetAuth)
|
||||
// 注意:根据你的协议文档,这里可能是 0x04 或 0x12
|
||||
// Android 代码中使用的是 0x12
|
||||
// _tcpClient.sendnew(
|
||||
// // MachineProtocolConstants.cmdGetAuth, // 0x04 或 0x12,根据实际协议调整
|
||||
// jsonBytes,
|
||||
// );
|
||||
// 构造完整的协议包
|
||||
final packet = buildSwitchControlPacket(jsonBytes);
|
||||
|
||||
debugPrint(
|
||||
'sendSwitchControlRequest[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}',
|
||||
);
|
||||
|
||||
// 发送数据包
|
||||
_tcpClient.sendnew(packet);
|
||||
|
||||
debugPrint(
|
||||
'✅ sendSwitchControlRequest[TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP][获取权限] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})',
|
||||
'[ControlPermission] local socket write completed device=' +
|
||||
deviceName +
|
||||
' cmd=0x12 bytes=' +
|
||||
packet.length.toString() +
|
||||
'; server/Web receipt unconfirmed',
|
||||
shouldLog: true,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('❌ sendSwitchControlRequest[TCP] 发送权限请求失败:$e');
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP][获取权限] 发送权限请求失败:$e',
|
||||
level: 'ERROR',
|
||||
shouldLog: true,
|
||||
);
|
||||
rethrow;
|
||||
ControlPermissionDiagnostics.event('TCP申请本地异常', {
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'delivery': 'unknown',
|
||||
});
|
||||
// A partial write may already have reached the peer; do not claim "not sent".
|
||||
throw ControlPermissionFailure('permission_send_uncertain');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,9 +117,7 @@ class RemoteTcpDatasource {
|
||||
|
||||
// TODO: 同意授权和拒绝授权
|
||||
void sendSwitchControlResponse(bool agreed, String deviceId) {
|
||||
debugPrint(
|
||||
'📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId',
|
||||
);
|
||||
debugPrint('📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId');
|
||||
|
||||
// 🔥 添加详细的连接状态日志
|
||||
debugPrint(
|
||||
@@ -177,7 +163,10 @@ class RemoteTcpDatasource {
|
||||
// 构造完整的协议包
|
||||
final packet = buildSwitchControlPacket(jsonBytes);
|
||||
|
||||
_logger.logWithLevel('TCP DataSource] JSON 数据: $jsonStr' ,shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'TCP DataSource] JSON 数据: $jsonStr',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
debugPrint(
|
||||
'📦 [TCP DataSource] 完整数据包(${packet.length}字节): ${packet.map((b) => '0x${b.toRadixString(16).padLeft(2, "0")}').join(' ')}',
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../../core/logging/remote_control_diagnostics.dart';
|
||||
import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/protocol/machine_protocol_codec.dart';
|
||||
@@ -34,10 +36,14 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
bool sendControlMachineCmd(MachineControlStatusEntity status) {
|
||||
// 🔥 整个“换算 + 编码 + 写 socket”都包在 try 里:本方法被 200ms 控制循环
|
||||
Future<bool> sendControlMachineCmd(
|
||||
MachineControlStatusEntity status, {
|
||||
bool priority = false,
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
// 🔥 整个“换算 + 编码 + 写 socket”都包在 try 里:本方法被 250ms 控制循环
|
||||
// 和停止风暴(一次 30 帧)高频调用,任何一帧抛异常都会变成 Timer 回调
|
||||
// 里的未捕获异常(每 200ms 刷一次),更糟的是会让 stopAllMovement 的
|
||||
// 里的未捕获异常(每 250ms 刷一次),更糟的是会让 stopAllMovement 的
|
||||
// 停止帧中途断掉——车就停不下来。失败一律返回 false,由调用方统计
|
||||
// “一共出网了几帧”(控制循环里本来就不关心返回值)。
|
||||
try {
|
||||
@@ -56,6 +62,26 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
emergency: status.isEmergency ? 1 : 0,
|
||||
);
|
||||
|
||||
try {
|
||||
final encoded = ByteData.sublistView(payload);
|
||||
RemoteControlDiagnostics.instance.event('conversion', {
|
||||
'x': status.originX,
|
||||
'y': status.originY,
|
||||
'linearMps': linear,
|
||||
'angularRadps': angular,
|
||||
'encodedLinearMps': encoded.getFloat64(0, Endian.little),
|
||||
'encodedAngularRadps': encoded.getFloat64(8, Endian.little),
|
||||
'payloadBytes': payload.length,
|
||||
'payloadHex': _hex(payload),
|
||||
'lift': status.chassisLift,
|
||||
'mower': status.mowerSpeed,
|
||||
'ignition': status.ignitionStatus,
|
||||
'emergency': status.isEmergency,
|
||||
});
|
||||
} catch (_) {
|
||||
// Observing the encoded payload cannot prevent its transmission.
|
||||
}
|
||||
|
||||
// 联调日志:三段式打印 ①滑块/摇杆原始数据 ②乘完系数的发送值 ③包装后的整帧字节(联调结束可移除)
|
||||
_logger.logWithLevel(
|
||||
'🔗 [联调-0x00] 遥控发送明细\n'
|
||||
@@ -73,9 +99,10 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
// 3. 调用 TcpClient 发送指令
|
||||
// 🔥 把写入结果如实上抛:false 代表本帧没交给系统 socket(未连接/写入异常),
|
||||
// 调用方(尤其 stopAllMovement 的停止风暴)需要知道“发出去了几个”。
|
||||
return _tcpClient.sendRaw(
|
||||
MachineProtocolConstants.cmdRemoteControl,
|
||||
return await _tcpClient.sendControlPayload(
|
||||
payload,
|
||||
priority: priority,
|
||||
isCurrent: isCurrent,
|
||||
);
|
||||
} catch (e, s) {
|
||||
debugPrint('❌ [RemoteControl] 遥控指令构造/发送异常: $e');
|
||||
@@ -96,63 +123,19 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
Stream<RawPacket> get responseStream => _tcpClient.packetStream;
|
||||
|
||||
@override
|
||||
void sendTcpPermissionRequest(String deviceName) {
|
||||
// 🔥 RemoteTcpDatasource.sendSwitchControlRequest 在 TCP 未连接时是 throw 的,
|
||||
// 而本方法是在 requestControlPermissionS 的 result.fold(async 回调) 里调的:
|
||||
// fold 不会 await 那个回调的 Future,异常从这条路径出去就是彻底的未捕获
|
||||
// 异步异常(点“获取控制权”时断着 TCP 就会撞上)。抢占请求发不出去最坏
|
||||
// 只是等不到 0x12 回包,不该崩,故就地吞掉并留 ERROR 痕迹。
|
||||
try {
|
||||
_remoteTcp.sendSwitchControlRequest(deviceName);
|
||||
_logger.logWithLevel(
|
||||
'🔑 [RemoteControl] TCP已发送权限请求',
|
||||
shouldLog: true,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('❌ [RemoteControl] TCP 权限请求发送失败: $e');
|
||||
_logger.logWithLevel(
|
||||
'❌ [RemoteControl] TCP 权限请求发送失败(未连接): $e',
|
||||
level: 'ERROR',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
Future<void> sendTcpPermissionRequest(
|
||||
String deviceName, {
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
// Await the actual write so failures reach the request UI.
|
||||
await _remoteTcp.sendSwitchControlRequest(deviceName, isCurrent: isCurrent);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> requestControlPermission(
|
||||
String deviceName,
|
||||
String deviceId,
|
||||
) async {
|
||||
try {
|
||||
// 1. 先发送 HTTP 权限请求检查权限
|
||||
_logger.logWithLevel(
|
||||
'🔑 [RemoteControl] 检查 HTTP 权限... deviceName=$deviceName, platform=$deviceId',
|
||||
shouldLog: true,
|
||||
);
|
||||
final result = await _remoteHttp.requestRemoteControlViaHttp(
|
||||
deviceName,
|
||||
deviceId,
|
||||
);
|
||||
|
||||
// 2. 如果没有权限或权限为 null,才发送 TCP 请求
|
||||
final hasPermission = result['hasPermission'] as bool? ?? false;
|
||||
_logger.logWithLevel(
|
||||
'🔑 [RemoteControl] HTTP权限查询结果: hasPermission=$hasPermission, owner=${result['owner']}',
|
||||
shouldLog: true,
|
||||
);
|
||||
if (!hasPermission) {
|
||||
_logger.logWithLevel('🔑 [RemoteControl] 无权限,发送 TCP 权限请求', shouldLog: true);
|
||||
_remoteTcp.sendSwitchControlRequest(deviceName);
|
||||
} else {
|
||||
_logger.logWithLevel('✅ [RemoteControl] 已有权限,无需 TCP 请求', shouldLog: true);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [RemoteControl] 权限请求失败:$e', level: 'ERROR', shouldLog: true);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
) => _remoteHttp.requestRemoteControlViaHttp(deviceName, deviceId);
|
||||
|
||||
@override
|
||||
void respondPermission(bool agreed, String deviceId) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/error/failure.dart';
|
||||
|
||||
/// A local failure classification; never adds fields to the wire protocol.
|
||||
class ControlPermissionFailure extends Failure implements Exception {
|
||||
final String feedbackKey;
|
||||
|
||||
ControlPermissionFailure(this.feedbackKey) : super(feedbackKey);
|
||||
|
||||
@override
|
||||
String toString() => feedbackKey;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ class MachineControlStatusEntity extends Equatable {
|
||||
final int originX;
|
||||
final int originY;
|
||||
final int chassisLift; // 0:停, 1:上, 2:下
|
||||
final int mowerSpeed; // 0:停, 1:+, 2:-
|
||||
final int mowerSpeed; // 0:关闭, 1:开启, 2:不操作
|
||||
final int ignitionStatus; // 0:停, 1:火, 2:熄
|
||||
final bool isEmergency;
|
||||
|
||||
@@ -12,7 +12,7 @@ class MachineControlStatusEntity extends Equatable {
|
||||
this.originX = 0,
|
||||
this.originY = 0,
|
||||
this.chassisLift = 0,
|
||||
this.mowerSpeed = 0,
|
||||
this.mowerSpeed = 2,
|
||||
this.ignitionStatus = 0,
|
||||
this.isEmergency = false,
|
||||
});
|
||||
|
||||
@@ -2,13 +2,16 @@ import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../domain/entities/machine_control_status_entity.dart';
|
||||
|
||||
abstract class RemoteControlRepository {
|
||||
/// 高频发送遥控指令 (被 Cubit 的 200ms 定时器调用)
|
||||
/// 高频发送遥控指令 (被 Cubit 的 250ms 定时器调用)
|
||||
/// 负责将 Entity 转换为底层的 0x00 指令并发出
|
||||
///
|
||||
/// 返回 `false` = 本帧未交给系统 socket(未连接或写入失败)。
|
||||
/// 🔥 安全路径(stopAllMovement / 急停帧)必须据此判断指令是否真出网,
|
||||
/// 不可再假定「调用了就等于设备收到了」。
|
||||
bool sendControlMachineCmd(MachineControlStatusEntity status);
|
||||
/// All 0x00 frames share the >=250ms sender. False also includes a stale or
|
||||
/// superseded request; success is local completion, never a machine ACK.
|
||||
Future<bool> sendControlMachineCmd(
|
||||
MachineControlStatusEntity status, {
|
||||
bool priority = false,
|
||||
bool Function()? isCurrent,
|
||||
});
|
||||
|
||||
/// 暴露解析后的回包流 (如 0x12 权限申请)
|
||||
/// UI 或 Cubit 监听此流来处理机器人主动推送的消息
|
||||
@@ -19,10 +22,16 @@ abstract class RemoteControlRepository {
|
||||
|
||||
/// 新增:请求控制权限 (HTTP接口返回完整权限信息)
|
||||
/// 返回: {hasPermission: bool, owner: String?}
|
||||
Future<Map<String, dynamic>> requestControlPermission(String deviceName, String deviceId);
|
||||
Future<Map<String, dynamic>> requestControlPermission(
|
||||
String deviceName,
|
||||
String deviceId,
|
||||
);
|
||||
|
||||
/// 🔥 新增: 发送 TCP 0x12 权限请求指令
|
||||
void sendTcpPermissionRequest(String deviceName);
|
||||
Future<void> sendTcpPermissionRequest(
|
||||
String deviceName, {
|
||||
bool Function()? isCurrent,
|
||||
});
|
||||
|
||||
/// 新增:响应控制权限 同意和拒绝(发送 0x05 指令)
|
||||
void respondPermission(bool bool, String deviceId);
|
||||
|
||||
@@ -4,24 +4,31 @@ import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
|
||||
|
||||
import '../repositories/remote_control_repository.dart';
|
||||
import '../entities/control_permission_failure.dart';
|
||||
|
||||
class RequestControlPermissionUseCase extends BaseUseCase<Map<String, dynamic>, RequestControlPermissionParams> {
|
||||
class RequestControlPermissionUseCase
|
||||
extends BaseUseCase<Map<String, dynamic>, RequestControlPermissionParams> {
|
||||
final RemoteControlRepository repository;
|
||||
|
||||
RequestControlPermissionUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, Map<String, dynamic>>> call(RequestControlPermissionParams params) async {
|
||||
Future<Either<Failure, Map<String, dynamic>>> call(
|
||||
RequestControlPermissionParams params,
|
||||
) async {
|
||||
debugPrint(
|
||||
'🔑 [权限链][UseCase] 开始执行请求 - deviceName: ${params.deviceName}, platform: ${params.deviceId}',
|
||||
);
|
||||
try {
|
||||
final result = await repository.requestControlPermission(params.deviceName, params.deviceId);
|
||||
final result = await repository.requestControlPermission(
|
||||
params.deviceName,
|
||||
params.deviceId,
|
||||
);
|
||||
debugPrint('🔑 [权限链][UseCase] 请求成功,返回: $result');
|
||||
return right(result);
|
||||
} catch (e) {
|
||||
debugPrint('❌ [权限链][UseCase] 请求异常: $e');
|
||||
return left(Failure(e.toString()));
|
||||
return left(e is ControlPermissionFailure ? e : Failure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,4 +41,4 @@ class RequestControlPermissionParams {
|
||||
required this.deviceName,
|
||||
required this.deviceId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,12 +7,40 @@ import '../../domain/entities/reverse_camera_data.dart';
|
||||
|
||||
enum RemoteControlStatus { initial, controlling, error }
|
||||
|
||||
/// 本次遥控会话的最后一次用户操作,不代表设备已执行。
|
||||
enum MowerLastOperation { none, turnOn, turnOff }
|
||||
|
||||
enum PermissionRequestPhase {
|
||||
idle,
|
||||
checking,
|
||||
sending,
|
||||
waiting,
|
||||
granted,
|
||||
failed,
|
||||
timedOut,
|
||||
}
|
||||
|
||||
class RemoteControlState extends Equatable {
|
||||
final RemoteControlStatus status;
|
||||
final MachineControlStatusEntity controlEntity; // 控制业务实体
|
||||
final MowerLastOperation lastMowerOperation;
|
||||
final String? errorMessage;
|
||||
final bool hasPermission; // 是否获得 0x12 权限
|
||||
final PermissionRequestPhase permissionRequestPhase;
|
||||
final String permissionFeedbackKey;
|
||||
final int permissionFeedbackId;
|
||||
|
||||
bool get isPermissionRequestBusy =>
|
||||
permissionRequestPhase == PermissionRequestPhase.checking ||
|
||||
permissionRequestPhase == PermissionRequestPhase.sending ||
|
||||
permissionRequestPhase == PermissionRequestPhase.waiting;
|
||||
final bool isEmergency;
|
||||
final bool hasEmergencyStatus;
|
||||
|
||||
/// 本地急停请求状态,不代表已取得设备动作确认。
|
||||
final bool isEmergencyRequestPending;
|
||||
final bool emergencyRequestFailed;
|
||||
final String emergencyFeedbackKey;
|
||||
final bool isLocked;
|
||||
final int ping;
|
||||
final int battery; //电池量
|
||||
@@ -42,9 +70,17 @@ class RemoteControlState extends Equatable {
|
||||
const RemoteControlState({
|
||||
this.status = RemoteControlStatus.initial,
|
||||
required this.controlEntity,
|
||||
this.lastMowerOperation = MowerLastOperation.none,
|
||||
this.errorMessage,
|
||||
this.hasPermission = false,
|
||||
this.permissionRequestPhase = PermissionRequestPhase.idle,
|
||||
this.permissionFeedbackKey = '',
|
||||
this.permissionFeedbackId = 0,
|
||||
this.isEmergency = false,
|
||||
this.hasEmergencyStatus = false,
|
||||
this.isEmergencyRequestPending = false,
|
||||
this.emergencyRequestFailed = false,
|
||||
this.emergencyFeedbackKey = '',
|
||||
this.isLocked = false,
|
||||
this.ping = 0,
|
||||
this.battery = 0,
|
||||
@@ -70,9 +106,17 @@ class RemoteControlState extends Equatable {
|
||||
RemoteControlState copyWith({
|
||||
RemoteControlStatus? status,
|
||||
MachineControlStatusEntity? controlEntity,
|
||||
MowerLastOperation? lastMowerOperation,
|
||||
String? errorMessage,
|
||||
bool? hasPermission,
|
||||
PermissionRequestPhase? permissionRequestPhase,
|
||||
String? permissionFeedbackKey,
|
||||
int? permissionFeedbackId,
|
||||
bool? isEmergency,
|
||||
bool? hasEmergencyStatus,
|
||||
bool? isEmergencyRequestPending,
|
||||
bool? emergencyRequestFailed,
|
||||
String? emergencyFeedbackKey,
|
||||
bool? isLocked,
|
||||
int? ping,
|
||||
int? battery,
|
||||
@@ -90,15 +134,28 @@ class RemoteControlState extends Equatable {
|
||||
bool? topRightIsExpanded,
|
||||
bool? obstacleRecognitionFlag,
|
||||
DeviceEntity? targetDevice,
|
||||
bool clearTargetDevice = false,
|
||||
String? updateType,
|
||||
ReverseCameraData? reverseCamera,
|
||||
}) {
|
||||
return RemoteControlState(
|
||||
status: status ?? this.status,
|
||||
controlEntity: controlEntity ?? this.controlEntity,
|
||||
lastMowerOperation: lastMowerOperation ?? this.lastMowerOperation,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
hasPermission: hasPermission ?? this.hasPermission,
|
||||
permissionRequestPhase:
|
||||
permissionRequestPhase ?? this.permissionRequestPhase,
|
||||
permissionFeedbackKey:
|
||||
permissionFeedbackKey ?? this.permissionFeedbackKey,
|
||||
permissionFeedbackId: permissionFeedbackId ?? this.permissionFeedbackId,
|
||||
isEmergency: isEmergency ?? this.isEmergency,
|
||||
hasEmergencyStatus: hasEmergencyStatus ?? this.hasEmergencyStatus,
|
||||
isEmergencyRequestPending:
|
||||
isEmergencyRequestPending ?? this.isEmergencyRequestPending,
|
||||
emergencyRequestFailed:
|
||||
emergencyRequestFailed ?? this.emergencyRequestFailed,
|
||||
emergencyFeedbackKey: emergencyFeedbackKey ?? this.emergencyFeedbackKey,
|
||||
isLocked: isLocked ?? this.isLocked,
|
||||
ping: ping ?? this.ping,
|
||||
battery: battery ?? this.battery,
|
||||
@@ -113,11 +170,14 @@ class RemoteControlState extends Equatable {
|
||||
showRightPip: showRightPip ?? this.showRightPip,
|
||||
runningStatusModel: runningStatusModel ?? this.runningStatusModel,
|
||||
obstacleFlag: obstacleFlag ?? this.obstacleFlag,
|
||||
hasReceivedStatusPush: hasReceivedStatusPush ?? this.hasReceivedStatusPush,
|
||||
hasReceivedStatusPush:
|
||||
hasReceivedStatusPush ?? this.hasReceivedStatusPush,
|
||||
topRightIsExpanded: topRightIsExpanded ?? this.topRightIsExpanded,
|
||||
obstacleRecognitionFlag:
|
||||
obstacleRecognitionFlag ?? this.obstacleRecognitionFlag,
|
||||
targetDevice: targetDevice ?? this.targetDevice,
|
||||
targetDevice: clearTargetDevice
|
||||
? null
|
||||
: targetDevice ?? this.targetDevice,
|
||||
updateType: updateType, // 不使用 ??,因为我们想要 null 的时候就是 null
|
||||
reverseCamera: reverseCamera ?? this.reverseCamera,
|
||||
);
|
||||
@@ -127,9 +187,17 @@ class RemoteControlState extends Equatable {
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
controlEntity,
|
||||
lastMowerOperation,
|
||||
errorMessage,
|
||||
hasPermission,
|
||||
permissionRequestPhase,
|
||||
permissionFeedbackKey,
|
||||
permissionFeedbackId,
|
||||
isEmergency,
|
||||
hasEmergencyStatus,
|
||||
isEmergencyRequestPending,
|
||||
emergencyRequestFailed,
|
||||
emergencyFeedbackKey,
|
||||
isLocked,
|
||||
ping,
|
||||
battery,
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
import 'package:maibu_satabot_v2/core/env/env_config.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
@@ -19,6 +19,7 @@ import '../bloc/remote_control_cubit.dart';
|
||||
import '../bloc/remote_control_state.dart';
|
||||
import '../widgets/center_control_area.dart';
|
||||
import '../widgets/emergency_overlay.dart';
|
||||
import '../widgets/emergency_stop_button.dart';
|
||||
import '../widgets/left_joystick_area.dart';
|
||||
import '../widgets/right_joystick_area.dart';
|
||||
import '../widgets/driving_guide_overlay.dart';
|
||||
@@ -120,33 +121,30 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
// 🔥 离开安全模式:启动 90 秒倒计时
|
||||
GetIt.I<AuthCubit>().exitSafeMode();
|
||||
|
||||
// 释放远程控制权限(type=2:退出远程遥控页面释放)
|
||||
// Schedule the priority zero before ending control; release only after the
|
||||
// rate-limited stop finishes, so release cannot overtake the final stop.
|
||||
final pendingStop = _controlSessionStarted
|
||||
? _cubit.stopAllMovement(reason: 'page_dispose')
|
||||
: Future<void>.value();
|
||||
if (_controlSessionStarted) _cubit.stopControlLoop();
|
||||
final deviceId = _cubit.state.targetDevice?.deviceName;
|
||||
if (_controlSessionStarted && deviceId != null && deviceId.isNotEmpty) {
|
||||
_cubit.releasePermission(deviceId: deviceId, type: 2).then((success) {
|
||||
CapsuleToast.show(
|
||||
success
|
||||
? _l10n.translate('remote_control.toast_released')
|
||||
: _l10n.translate('remote_control.toast_release_failed'),
|
||||
showCheck: success,
|
||||
);
|
||||
});
|
||||
pendingStop
|
||||
.then((_) => _cubit.releasePermission(deviceId: deviceId, type: 2))
|
||||
.then((success) {
|
||||
CapsuleToast.show(
|
||||
success
|
||||
? _l10n.translate('remote_control.toast_released')
|
||||
: _l10n.translate('remote_control.toast_release_failed'),
|
||||
showCheck: success,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
_permissionSubscription?.cancel(); // 🔥 取消订阅
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
// 🔥 退页先把车真正停下:归零双轴 + 连发 30 帧停止指令。
|
||||
// 只靠 stopControlLoop() 断掉 200ms 循环是不够的:设备只认“最后收到的
|
||||
// 运动帧”,若手指还压在摇杆上就退出(没走松手归零),已下发的高速帧会
|
||||
// 让车继续跑到它自己的失联保护为止。与新版 HUD 折叠/退出的 deactivate()
|
||||
// 同一口径。
|
||||
// 必须放在 stopControlLoop() 之前:stopAllMovement 末尾会按 _controlWanted
|
||||
// 决定是否重启循环,这里同步把意图关掉,就不会在退页后留下无主定时器。
|
||||
if (_controlSessionStarted) {
|
||||
unawaited(_cubit.stopAllMovement());
|
||||
_cubit.stopControlLoop();
|
||||
}
|
||||
// The priority stop above uses the same >=250ms sender as normal movement.
|
||||
_cubit.stopReverseCameraMock(); // 🔥 停止倒车影像 Mock,避免定时器空转
|
||||
// 🔥 重置权限状态,避免单例 hasPermission 残留导致下次进入不再查询接口
|
||||
_cubit.resetPermissionState();
|
||||
@@ -158,6 +156,7 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
deviceId: _modeDeviceId,
|
||||
target: ControlModeTarget.remote,
|
||||
cancelToPreview: true,
|
||||
emergencyStopControl: const EmergencyStopButton(),
|
||||
onReady: () {
|
||||
if (_cubit.state.targetDevice?.deviceName != _modeDeviceId) return;
|
||||
_controlSessionStarted = true;
|
||||
@@ -229,7 +228,7 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
token != null &&
|
||||
token.isNotEmpty) {
|
||||
_videoStreamUrl =
|
||||
"webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=$token";
|
||||
"webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/$deviceId?token=$token";
|
||||
debugPrint('🎬 [WebRTC] URL构建成功: $_videoStreamUrl');
|
||||
} else {
|
||||
_videoStreamUrl = '';
|
||||
@@ -279,9 +278,11 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
),
|
||||
|
||||
BlocBuilder<RemoteControlCubit, RemoteControlState>(
|
||||
buildWhen: (p, c) => p.isEmergency != c.isEmergency,
|
||||
buildWhen: (p, c) =>
|
||||
p.isEmergency != c.isEmergency ||
|
||||
p.hasEmergencyStatus != c.hasEmergencyStatus,
|
||||
builder: (context, state) {
|
||||
return state.isEmergency
|
||||
return state.isEmergency && state.hasEmergencyStatus
|
||||
? const Positioned.fill(child: EmergencyOverlay())
|
||||
: const SizedBox.shrink();
|
||||
},
|
||||
@@ -300,6 +301,8 @@ class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
},
|
||||
buildWhen: (p, c) =>
|
||||
p.hasPermission != c.hasPermission ||
|
||||
p.permissionRequestPhase != c.permissionRequestPhase ||
|
||||
p.permissionFeedbackId != c.permissionFeedbackId ||
|
||||
p.isLocked != c.isLocked ||
|
||||
p.topRightIsExpanded != c.topRightIsExpanded ||
|
||||
p.obstacleRecognitionFlag != c.obstacleRecognitionFlag ||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'remote_control_link_feedback.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
import '../bloc/remote_control_state.dart';
|
||||
import 'emergency_stop_button.dart';
|
||||
|
||||
class CenterControlArea extends StatelessWidget {
|
||||
@@ -43,7 +45,7 @@ class CenterControlArea extends StatelessWidget {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
_buildSliderBox(expandedWidth, 'chassis', true,context),
|
||||
_buildSliderBox(expandedWidth, 'chassis', true, context),
|
||||
SizedBox(height: totalWidth * 0.01),
|
||||
],
|
||||
),
|
||||
@@ -60,7 +62,9 @@ class CenterControlArea extends StatelessWidget {
|
||||
SizedBox(height: totalWidth * 0.05),
|
||||
|
||||
Text(
|
||||
AppLocalizations.of(context).translate('remote_control.switch_view_hint'),
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.switch_view_hint'),
|
||||
style: const TextStyle(fontSize: 8, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
@@ -73,7 +77,31 @@ class CenterControlArea extends StatelessWidget {
|
||||
width: expandedWidth,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [_buildSliderBox(expandedWidth, 'mower', false,context)],
|
||||
children: [
|
||||
_buildSliderBox(expandedWidth, 'mower', false, context),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.mower_last_operation', {
|
||||
'operation': AppLocalizations.of(context).translate(
|
||||
switch (remoteState.lastMowerOperation) {
|
||||
MowerLastOperation.turnOn =>
|
||||
'remote_control.mower_operation_on',
|
||||
MowerLastOperation.turnOff =>
|
||||
'remote_control.mower_operation_off',
|
||||
MowerLastOperation.none =>
|
||||
'remote_control.mower_operation_none',
|
||||
},
|
||||
),
|
||||
}),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.65),
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -83,12 +111,17 @@ class CenterControlArea extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSliderBox(double boxWidth, String deviceKey, bool isLeft,BuildContext context) {
|
||||
Widget _buildSliderBox(
|
||||
double boxWidth,
|
||||
String deviceKey,
|
||||
bool isLeft,
|
||||
BuildContext context,
|
||||
) {
|
||||
// 🔥 使用deviceKey作为唯一标识,不依赖显示文本
|
||||
final label = deviceKey == 'chassis'
|
||||
final label = deviceKey == 'chassis'
|
||||
? AppLocalizations.of(context).translate('remote_control.chassis')
|
||||
: AppLocalizations.of(context).translate('remote_control.mower');
|
||||
|
||||
|
||||
return SizedBox(
|
||||
width: boxWidth,
|
||||
child: Center(
|
||||
@@ -98,7 +131,7 @@ class CenterControlArea extends StatelessWidget {
|
||||
child: CCExpandSlider(
|
||||
label: label,
|
||||
svgStart: "assets/svgs/remote_up.svg",
|
||||
svgCenter: deviceKey == 'mower'
|
||||
svgCenter: deviceKey == 'mower'
|
||||
? "assets/svgs/remote_scissors.svg"
|
||||
: "assets/svgs/remote_layers.svg",
|
||||
svgEnd: "assets/svgs/remote_down.svg",
|
||||
@@ -113,7 +146,12 @@ class CenterControlArea extends StatelessWidget {
|
||||
}
|
||||
|
||||
// 🔥 新增:统一的业务逻辑分发方法
|
||||
void _handleSliderAction(String deviceKey, String action, BuildContext context) {
|
||||
void _handleSliderAction(
|
||||
String deviceKey,
|
||||
String action,
|
||||
BuildContext context,
|
||||
) {
|
||||
RemoteControlLinkNotice.showIfDisconnected(context);
|
||||
debugPrint('🎯 [Slider 业务] deviceKey: $deviceKey, action: $action');
|
||||
|
||||
// 🔥 门槛检查:与摇杆一致,未收到 TCP 0x02 推送时禁止操作并提示。
|
||||
@@ -133,7 +171,7 @@ class CenterControlArea extends StatelessWidget {
|
||||
_handleMowerAction(action, context);
|
||||
break;
|
||||
default:
|
||||
debugPrint('⚠️ 未知的 deviceKey: $deviceKey');
|
||||
debugPrint('⚠️ 未知的 deviceKey: $deviceKey');
|
||||
}
|
||||
// 🔥 在指令执行后触发震动反馈(增强手感)
|
||||
HapticFeedback.mediumImpact();
|
||||
@@ -147,40 +185,34 @@ class CenterControlArea extends StatelessWidget {
|
||||
case "start":
|
||||
debugPrint('⬆️ 底盘 - 向上(例如:前进)');
|
||||
// TODO: 发送底盘前进指令
|
||||
cubit.sendChassisCommand(1);
|
||||
cubit.sendChassisCommand(1);
|
||||
break;
|
||||
case "center":
|
||||
debugPrint('️ 底盘 - 中间(例如:停止)');
|
||||
// TODO: 发送底盘停止指令
|
||||
cubit.sendChassisCommand(0);
|
||||
cubit.sendChassisCommand(0);
|
||||
break;
|
||||
case "end":
|
||||
debugPrint('⬇️ 底盘 - 向下(例如:后退)');
|
||||
// TODO: 发送底盘后退指令
|
||||
cubit.sendChassisCommand(2);
|
||||
cubit.sendChassisCommand(2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 割刀的业务逻辑(右滑块)
|
||||
// 割刀开关(右滑块);段位映射由 Cubit 统一处理。
|
||||
void _handleMowerAction(String action, BuildContext context) {
|
||||
final cubit = context.read<RemoteControlCubit>();
|
||||
|
||||
switch (action) {
|
||||
case "start":
|
||||
debugPrint('⬆️ 割刀 - 向上(例如:抬刀)');
|
||||
// TODO: 发送抬刀指令
|
||||
cubit.sendMowerCommand(1);
|
||||
cubit.sendMowerSliderCommand(1);
|
||||
break;
|
||||
case "center":
|
||||
debugPrint('⏹️ 割刀 - 中间(例如:保持)');
|
||||
// TODO: 发送保持指令
|
||||
cubit.sendMowerCommand(0);
|
||||
cubit.sendMowerSliderCommand(0);
|
||||
break;
|
||||
case "end":
|
||||
debugPrint('⬇️ 割刀 - 向下(例如:降刀)');
|
||||
// TODO: 发送降刀指令
|
||||
cubit.sendMowerCommand(2);
|
||||
cubit.sendMowerSliderCommand(2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,190 +3,141 @@ import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:vibration/vibration.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
import '../../../../components/capsule_toast.dart';
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
import 'emergency_stop_confirmation.dart';
|
||||
import '../../../device_control_mode/presentation/widgets/mode_independent_control.dart';
|
||||
|
||||
class EmergencyStopButton extends StatefulWidget {
|
||||
const EmergencyStopButton({super.key, this.width = 120});
|
||||
final double width;
|
||||
const EmergencyStopButton({
|
||||
Key? key,
|
||||
this.width = 120,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<EmergencyStopButton> createState() => _EmergencyStopButtonState();
|
||||
}
|
||||
|
||||
class _EmergencyStopButtonState extends State<EmergencyStopButton>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _progressController;
|
||||
bool _isPressing = false;
|
||||
class _EmergencyStopButtonState extends State<EmergencyStopButton> {
|
||||
bool _isConfirming = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_progressController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 3),
|
||||
);
|
||||
|
||||
// 添加监听器,确保动画值变化时重建 UI
|
||||
_progressController.addListener(() {
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
}
|
||||
});
|
||||
Future<void> _confirmAndSubmitEmergency(bool on) async {
|
||||
final cubit = context.read<RemoteControlCubit>();
|
||||
if (_isConfirming || cubit.state.isEmergencyRequestPending) return;
|
||||
if (!cubit.checkEmergencyRequest(on)) {
|
||||
CapsuleToast.show(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.${cubit.state.emergencyFeedbackKey}'),
|
||||
showCheck: false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
final sn = cubit.state.targetDevice?.deviceName;
|
||||
_isConfirming = true;
|
||||
bool confirmed;
|
||||
try {
|
||||
confirmed = await confirmEmergencyStop(context, engage: on, sn: sn ?? '');
|
||||
} finally {
|
||||
_isConfirming = false;
|
||||
}
|
||||
if (!confirmed || !mounted || sn != cubit.state.targetDevice?.deviceName) {
|
||||
return;
|
||||
}
|
||||
await cubit.updateEmergency(on);
|
||||
if (!mounted || sn != cubit.state.targetDevice?.deviceName) return;
|
||||
final key = cubit.state.emergencyFeedbackKey;
|
||||
if (key.isNotEmpty) {
|
||||
CapsuleToast.show(
|
||||
AppLocalizations.of(context).translate('remote_control.$key'),
|
||||
showCheck: false,
|
||||
duration: const Duration(seconds: 3),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_progressController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _resetProgress() {
|
||||
setState(() => _isPressing = false);
|
||||
_progressController.stop();
|
||||
_progressController.value = 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isEmergencyActive = context
|
||||
.watch<RemoteControlCubit>()
|
||||
.state
|
||||
.isEmergency;
|
||||
Widget build(BuildContext context) =>
|
||||
ModeIndependentControl(child: _buildButton(context));
|
||||
|
||||
Widget _buildButton(BuildContext context) {
|
||||
final state = context.watch<RemoteControlCubit>().state;
|
||||
final active = state.isEmergency;
|
||||
final pending = state.isEmergencyRequestPending;
|
||||
final width = widget.width * 0.65;
|
||||
final double indicatorSize = width + 20;
|
||||
|
||||
return SizedBox(
|
||||
width: indicatorSize,
|
||||
height: indicatorSize,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// 进度环 - 只在按压时显示
|
||||
AnimatedOpacity(
|
||||
opacity: _isPressing ? 1.0 : 0.0,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: SizedBox(
|
||||
width: indicatorSize,
|
||||
height: indicatorSize,
|
||||
child: CircularProgressIndicator(
|
||||
value: _progressController.value,
|
||||
strokeWidth: 6,
|
||||
color: Colors.red.withOpacity(0.9),
|
||||
backgroundColor: Colors.red.withValues(alpha: 0.2),
|
||||
),
|
||||
width: width + 20,
|
||||
height: width + 20,
|
||||
child: Center(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: pending
|
||||
? null
|
||||
: () {
|
||||
HapticFeedback.heavyImpact();
|
||||
_vibrate();
|
||||
_confirmAndSubmitEmergency(!active);
|
||||
},
|
||||
child: Container(
|
||||
width: width,
|
||||
height: width,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: active
|
||||
? Colors.red.withValues(alpha: 0.5)
|
||||
: const Color(0x80C53030),
|
||||
boxShadow: active
|
||||
? [
|
||||
BoxShadow(
|
||||
color: Colors.red.withValues(alpha: 0.5),
|
||||
blurRadius: 20,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
|
||||
// 按钮主体
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
debugPrint('🔴 [点击] 触发急停');
|
||||
_triggerVibration();
|
||||
if (!isEmergencyActive) {
|
||||
context.read<RemoteControlCubit>().updateEmergency(true);
|
||||
context.read<RemoteControlCubit>().toggleLock();
|
||||
HapticFeedback.heavyImpact();
|
||||
}
|
||||
},
|
||||
onLongPressStart: (_) {
|
||||
debugPrint('🔴 [长按开始] isEmergency=$isEmergencyActive');
|
||||
_triggerVibration();
|
||||
if (isEmergencyActive && !_isPressing) {
|
||||
setState(() => _isPressing = true);
|
||||
debugPrint('🔴 [开始动画] 从 0 开始');
|
||||
_triggerVibration();
|
||||
_progressController.reset();
|
||||
_progressController.forward().then((_) {
|
||||
debugPrint('🔴 [动画完成] _isPressing=$_isPressing');
|
||||
if (_isPressing && mounted) {
|
||||
debugPrint('✅ [解除急停] 执行');
|
||||
_triggerVibration();
|
||||
context.read<RemoteControlCubit>().updateEmergency(false);
|
||||
context.read<RemoteControlCubit>().toggleLock();
|
||||
HapticFeedback.vibrate();
|
||||
setState(() => _isPressing = false);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
onLongPressEnd: (_) {
|
||||
_triggerVibration();
|
||||
debugPrint('🔴 [长按结束]');
|
||||
if (_isPressing) {
|
||||
_resetProgress();
|
||||
|
||||
}
|
||||
},
|
||||
onLongPressCancel: () {
|
||||
_triggerVibration();
|
||||
debugPrint('🔴 [长按取消]');
|
||||
if (_isPressing) {
|
||||
_resetProgress();
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
width: width,
|
||||
height: width,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isEmergencyActive
|
||||
? Colors.red.withOpacity(0.5)
|
||||
: const Color(0x80C53030),
|
||||
boxShadow: isEmergencyActive
|
||||
? [
|
||||
BoxShadow(
|
||||
color: Colors.red.withValues(alpha: 0.5),
|
||||
blurRadius: 20,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
'assets/svgs/remote_alert.svg',
|
||||
width: width * 0.4,
|
||||
colorFilter: ColorFilter.mode(
|
||||
Colors.white.withValues(alpha: 0.5),
|
||||
BlendMode.srcIn,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SvgPicture.asset(
|
||||
'assets/svgs/remote_alert.svg',
|
||||
width: width * 0.4,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
AppLocalizations.of(context).translate(
|
||||
pending
|
||||
? 'remote_control.emergency_submitting'
|
||||
: !state.hasEmergencyStatus
|
||||
? 'remote_control.emergency_unknown'
|
||||
: active
|
||||
? 'remote_control.emergency_stopping'
|
||||
: 'remote_control.emergency_inactive',
|
||||
),
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.5),
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
isEmergencyActive
|
||||
? AppLocalizations.of(context).translate('remote_control.emergency_stopping')
|
||||
: AppLocalizations.of(context).translate('remote_control.emergency_stop'),
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.5),
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _triggerVibration() {
|
||||
Vibration.hasVibrator().then((hasVibrator) {
|
||||
if (hasVibrator ?? false) {
|
||||
Vibration.vibrate(duration: 50, amplitude: 380);
|
||||
debugPrint(' 震动执行 - 10ms');
|
||||
} else {
|
||||
debugPrint(' 设备不支持震动');
|
||||
Future<void> _vibrate() async {
|
||||
try {
|
||||
if (await Vibration.hasVibrator()) {
|
||||
await Vibration.vibrate(duration: 50, amplitude: 255);
|
||||
}
|
||||
}).catchError((e) {
|
||||
debugPrint('震动失败:$e');
|
||||
});
|
||||
} catch (_) {
|
||||
// 无震动能力时仍可正常发起急停请求。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
|
||||
/// 只确认用户意图;关闭、返回或取消弹窗均不发送控制请求。
|
||||
Future<bool> confirmEmergencyStop(
|
||||
BuildContext context, {
|
||||
required bool engage,
|
||||
required String sn,
|
||||
}) async {
|
||||
final tr = AppLocalizations.of(context);
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(
|
||||
tr.translate(
|
||||
engage
|
||||
? 'remote_control.emergency_confirm_title'
|
||||
: 'remote_control.emergency_release_title',
|
||||
),
|
||||
),
|
||||
content: Text(
|
||||
tr.translate(
|
||||
engage
|
||||
? 'remote_control.emergency_confirm_message'
|
||||
: 'remote_control.emergency_release_message',
|
||||
{'sn': sn},
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: const ValueKey('emergency-cancel'),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: Text(tr.translate('remote_control.emergency_cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
key: const ValueKey('emergency-confirm'),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: Text(
|
||||
tr.translate(
|
||||
engage
|
||||
? 'remote_control.emergency_confirm_stop'
|
||||
: 'remote_control.emergency_confirm_release',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import '../../../../core/logging/remote_control_diagnostics.dart';
|
||||
import 'dart:async';
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'remote_control_link_feedback.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:vibration/vibration.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
@@ -28,6 +30,10 @@ class _LeftJoystickAreaState extends State<LeftJoystickArea> {
|
||||
|
||||
/// 检查是否可以控制,不能则弹出提示
|
||||
bool _checkCanControl(BuildContext context) {
|
||||
if (!_hasShownNoPushDialog &&
|
||||
RemoteControlLinkNotice.showIfDisconnected(context)) {
|
||||
_hasShownNoPushDialog = true;
|
||||
}
|
||||
// 🔥 临时关闭「未收到推送不能控制」门槛,便于机器未开时用 Mock 假数据联调倒车影像。
|
||||
// 联调完成后取消下面注释即可恢复。切勿删除本段逻辑。
|
||||
// final cubit = context.read<RemoteControlCubit>();
|
||||
@@ -88,6 +94,7 @@ class _LeftJoystickAreaState extends State<LeftJoystickArea> {
|
||||
child: CCJoystick(
|
||||
radius: widget.width,
|
||||
axisHint: AxisHint.forwardBackward,
|
||||
onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields),
|
||||
onValueChanged: (value) {
|
||||
if (!_checkCanControl(context)) return;
|
||||
// 标记:正在触摸
|
||||
@@ -135,7 +142,7 @@ class _LeftJoystickAreaState extends State<LeftJoystickArea> {
|
||||
debugPrint('✅ 摇杆已停止 -> 强制 X=0, Y=0 停车');
|
||||
|
||||
// 🔥 使用安全方法,一次性清零双轴,确保只发送 (X=0, Y=0)
|
||||
await context.read<RemoteControlCubit>().stopAllMovement();
|
||||
await context.read<RemoteControlCubit>().stopAllMovement(reason: 'forward_release');
|
||||
}
|
||||
|
||||
void _triggerVibration() {
|
||||
@@ -143,4 +150,4 @@ class _LeftJoystickAreaState extends State<LeftJoystickArea> {
|
||||
if (has ?? false) Vibration.vibrate(duration: 12);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../components/capsule_toast.dart';
|
||||
import '../../../../core/localization/app_localizations.dart';
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
import '../bloc/remote_control_state.dart';
|
||||
|
||||
/// Shared by both control entry points. Telemetry rebuilds never repeat a toast.
|
||||
class PermissionRequestFeedback extends StatelessWidget {
|
||||
const PermissionRequestFeedback({
|
||||
super.key,
|
||||
required this.cubit,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final RemoteControlCubit cubit;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
BlocListener<RemoteControlCubit, RemoteControlState>(
|
||||
bloc: cubit,
|
||||
listenWhen: (previous, current) =>
|
||||
previous.permissionFeedbackId != current.permissionFeedbackId &&
|
||||
current.permissionFeedbackKey.isNotEmpty,
|
||||
listener: (context, state) => CapsuleToast.show(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.' + state.permissionFeedbackKey),
|
||||
duration: const Duration(seconds: 3),
|
||||
showCheck:
|
||||
state.permissionRequestPhase == PermissionRequestPhase.granted,
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
String permissionStatusText(BuildContext context, RemoteControlState state) {
|
||||
final key = switch (state.permissionRequestPhase) {
|
||||
PermissionRequestPhase.checking => 'permission_checking',
|
||||
PermissionRequestPhase.sending => 'permission_sending',
|
||||
PermissionRequestPhase.waiting => 'permission_waiting',
|
||||
PermissionRequestPhase.timedOut => 'permission_unconfirmed',
|
||||
PermissionRequestPhase.failed when !state.hasPermission =>
|
||||
'permission_request_failed',
|
||||
_ => state.hasPermission ? 'controlling' : 'not_controlling',
|
||||
};
|
||||
return AppLocalizations.of(context).translate('remote_control.' + key);
|
||||
}
|
||||
|
||||
String permissionStatusHint(BuildContext context, RemoteControlState state) =>
|
||||
state.permissionFeedbackKey.isEmpty
|
||||
? permissionStatusText(context, state)
|
||||
: AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.' + state.permissionFeedbackKey);
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
/// 只展示已有连接收到的心跳,不发送数据,也不参与重连或控制门控。
|
||||
class RemoteControlHeartbeatIndicator extends StatefulWidget {
|
||||
const RemoteControlHeartbeatIndicator({
|
||||
super.key,
|
||||
required this.heartbeats,
|
||||
this.size = 10,
|
||||
});
|
||||
|
||||
final Stream<void> heartbeats;
|
||||
final double size;
|
||||
|
||||
@override
|
||||
State<RemoteControlHeartbeatIndicator> createState() =>
|
||||
_RemoteControlHeartbeatIndicatorState();
|
||||
}
|
||||
|
||||
class _RemoteControlHeartbeatIndicatorState
|
||||
extends State<RemoteControlHeartbeatIndicator> {
|
||||
StreamSubscription<void>? _subscription;
|
||||
Timer? _pulseTimer;
|
||||
bool _lit = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_listen();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(RemoteControlHeartbeatIndicator oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.heartbeats != widget.heartbeats) {
|
||||
_subscription?.cancel();
|
||||
_pulseTimer?.cancel();
|
||||
_lit = false;
|
||||
_listen();
|
||||
}
|
||||
}
|
||||
|
||||
void _listen() {
|
||||
_subscription = widget.heartbeats.listen((_) {
|
||||
if (!mounted) return;
|
||||
_pulseTimer?.cancel();
|
||||
setState(() => _lit = true);
|
||||
_pulseTimer = Timer(const Duration(milliseconds: 300), () {
|
||||
if (mounted) setState(() => _lit = false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subscription?.cancel();
|
||||
_pulseTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Tooltip(
|
||||
message: AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.tcp_heartbeat'),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(6),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 100),
|
||||
width: widget.size,
|
||||
height: widget.size,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: _lit ? const Color(0xFF36C878) : const Color(0xFF86909C),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 操作时读取现有 TCP 连接状态,仅提示,不拦截、不重连、不改变指令。
|
||||
class RemoteControlLinkNotice {
|
||||
static DateTime? _lastShownAt;
|
||||
|
||||
static bool showIfDisconnected(BuildContext context) {
|
||||
if (sl<RemoteControlCubit>().isControlLinkConnected) return false;
|
||||
final now = DateTime.now();
|
||||
if (_lastShownAt == null ||
|
||||
now.difference(_lastShownAt!) >= const Duration(seconds: 2)) {
|
||||
_lastShownAt = now;
|
||||
CapsuleToast.show(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.tcp_unavailable'),
|
||||
showCheck: false,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import '../../../../core/logging/remote_control_diagnostics.dart';
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'remote_control_link_feedback.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:vibration/vibration.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
@@ -27,6 +29,10 @@ class _RightJoystickAreaState extends State<RightJoystickArea> {
|
||||
|
||||
/// 检查是否可以控制,不能则弹出提示
|
||||
bool _checkCanControl(BuildContext context) {
|
||||
if (!_hasShownNoPushDialog &&
|
||||
RemoteControlLinkNotice.showIfDisconnected(context)) {
|
||||
_hasShownNoPushDialog = true;
|
||||
}
|
||||
// 🔥 临时关闭「未收到推送不能控制」门槛,便于机器未开时用 Mock 假数据联调倒车影像。
|
||||
// 联调完成后取消下面注释即可恢复。切勿删除本段逻辑。
|
||||
// final cubit = context.read<RemoteControlCubit>();
|
||||
@@ -87,6 +93,7 @@ class _RightJoystickAreaState extends State<RightJoystickArea> {
|
||||
child: CCJoystick(
|
||||
radius: widget.width,
|
||||
axisHint: AxisHint.leftRight,
|
||||
onDiagnostic: (event, fields) => RemoteControlDiagnostics.instance.event('joystick_' + event, fields),
|
||||
onValueChanged: (value) {
|
||||
if (!_checkCanControl(context)) return;
|
||||
int currentX = value.x.toInt();
|
||||
@@ -107,7 +114,7 @@ class _RightJoystickAreaState extends State<RightJoystickArea> {
|
||||
_lastX = 0;
|
||||
|
||||
// 🔥 使用安全方法,一次性清零双轴,确保只发送 (X=0, Y=0)
|
||||
await context.read<RemoteControlCubit>().stopAllMovement();
|
||||
await context.read<RemoteControlCubit>().stopAllMovement(reason: 'turn_release');
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -128,4 +135,4 @@ class _RightJoystickAreaState extends State<RightJoystickArea> {
|
||||
void _triggerVibration() {
|
||||
Vibration.vibrate(duration: 12);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../devices/domain/entities/device_entity.dart';
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
import '../../data/models/running_status_model.dart';
|
||||
import 'remote_control_link_feedback.dart';
|
||||
import 'permission_request_feedback.dart';
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
class TopStatusBar extends StatelessWidget {
|
||||
@@ -83,41 +85,37 @@ class TopStatusBar extends StatelessWidget {
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// 2. 控制状态 (对应 StatusChipLeft)
|
||||
StatusChip(
|
||||
text: remoteState.hasPermission
|
||||
? AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.controlling')
|
||||
: AppLocalizations.of(
|
||||
context,
|
||||
).translate('remote_control.not_controlling'),
|
||||
color: remoteState.hasPermission
|
||||
? const Color(0xFF1DB954)
|
||||
: Colors.red,
|
||||
icon: Icons.eighteen_mp,
|
||||
breathing: !remoteState.hasPermission,
|
||||
onTap: () {
|
||||
if (!remoteState.hasPermission) {
|
||||
// 🔥 点击后发起抢占:查权限 + 无权限则发 TCP switch_control
|
||||
debugPrint('🔑 [TopStatusBar] 👆 用户手动点击“未在控制”,请求抢占控制权');
|
||||
final targetDevice =
|
||||
_remoteControlCubit.state.targetDevice;
|
||||
if (targetDevice != null) {
|
||||
PermissionRequestFeedback(
|
||||
cubit: _remoteControlCubit,
|
||||
child: Tooltip(
|
||||
message: permissionStatusHint(context, remoteState),
|
||||
child: StatusChip(
|
||||
text: permissionStatusText(context, remoteState),
|
||||
color: remoteState.isPermissionRequestBusy
|
||||
? Colors.orange
|
||||
: remoteState.hasPermission
|
||||
? const Color(0xFF1DB954)
|
||||
: Colors.red,
|
||||
icon: Icons.eighteen_mp,
|
||||
breathing: !remoteState.hasPermission,
|
||||
onTap: () {
|
||||
if (remoteState.hasPermission || remoteState.isPermissionRequestBusy) return;
|
||||
_remoteControlCubit.requestControlPermissionS(
|
||||
targetDevice.deviceName,
|
||||
_remoteControlCubit.state.targetDevice?.deviceName ?? '',
|
||||
'app',
|
||||
source: '手动点击',
|
||||
grabControl: true,
|
||||
);
|
||||
} else {
|
||||
debugPrint('❌ [TopStatusBar] targetDevice 为空,无法请求权限');
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// 3. 锁定状态 (对应 SmallFunctionButton)
|
||||
RemoteControlHeartbeatIndicator(
|
||||
heartbeats: _remoteControlCubit.serverHeartbeats,
|
||||
),
|
||||
_buildIconButton(
|
||||
remoteState.isLocked
|
||||
? "assets/svgs/remote_lock.svg"
|
||||
@@ -476,6 +474,7 @@ class TopStatusBar extends StatelessWidget {
|
||||
|
||||
// 🔥 新增:统一的业务逻辑分发方法
|
||||
void _handleSliderAction(String label, String action, BuildContext context) {
|
||||
RemoteControlLinkNotice.showIfDisconnected(context);
|
||||
debugPrint('🎯 [Slider 业务] label: $label, action: $action');
|
||||
|
||||
// 🔥 根据 label 区分不同的设备
|
||||
|
||||
@@ -615,6 +615,20 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
modeText,
|
||||
l10n.translate('device_detail_v2.stat_control_mode'),
|
||||
),
|
||||
_statCard(
|
||||
Icons.emergency_outlined,
|
||||
st?.emergencyStop == null
|
||||
? '--'
|
||||
: l10n.translate(
|
||||
st!.emergencyStop!
|
||||
? 'device_detail_v2.emergency_stop_active'
|
||||
: 'device_detail_v2.emergency_stop_inactive',
|
||||
),
|
||||
l10n.translate('device_detail_v2.stat_emergency_stop'),
|
||||
valueColor: st?.emergencyStop == true
|
||||
? const Color(0xFFDC2626)
|
||||
: _navy,
|
||||
),
|
||||
_statCard(
|
||||
Icons.thermostat_outlined,
|
||||
st == null ? '--' : '${st.chipTemp.toStringAsFixed(1)}°',
|
||||
@@ -678,25 +692,21 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: tiles[0]),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: tiles[1]),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: tiles[2]),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: tiles[3]),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: tiles[4]),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(child: tiles[5]),
|
||||
],
|
||||
),
|
||||
for (var row = 0; row < tiles.length; row += 3) ...[
|
||||
if (row > 0) const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
for (var column = 0; column < 3; column++) ...[
|
||||
if (column > 0) const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: row + column < tiles.length
|
||||
? tiles[row + column]
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -733,6 +743,7 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
String value,
|
||||
String label, {
|
||||
double valueFontSize = 16,
|
||||
Color? valueColor,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4),
|
||||
@@ -752,7 +763,7 @@ class _DeviceDetailPageV2State extends State<DeviceDetailPageV2> {
|
||||
style: TextStyle(
|
||||
fontSize: valueFontSize,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: _navy,
|
||||
color: valueColor ?? _navy,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
|
||||
Reference in New Issue
Block a user