完善遥控权限、控制发送和急停反馈
This commit is contained in:
@@ -336,6 +336,27 @@
|
||||
},
|
||||
|
||||
"remote_control": {
|
||||
"permission_checking": "Checking…",
|
||||
"permission_sending": "Requesting…",
|
||||
"permission_waiting": "Awaiting response…",
|
||||
"permission_unconfirmed": "Unconfirmed",
|
||||
"permission_request_failed": "Request unsuccessful",
|
||||
"permission_invalid_device": "Cannot request control: no target device",
|
||||
"permission_auth_required": "Your sign-in has expired. Please sign in again.",
|
||||
"permission_query_invalid": "Invalid permission response. Please retry.",
|
||||
"permission_query_rejected": "Permission check unsuccessful. Please retry later.",
|
||||
"permission_query_timeout": "Permission check timed out. Please retry.",
|
||||
"permission_query_failed": "Permission check failed. Check your network and retry.",
|
||||
"permission_tcp_disconnected": "Request not sent: TCP is disconnected",
|
||||
"permission_send_uncertain": "Send error. Delivery is unconfirmed. Please retry later.",
|
||||
"permission_sent": "Control request sent via TCP. Awaiting a response.",
|
||||
"permission_already_granted": "You already have control",
|
||||
"permission_granted": "Control acquired",
|
||||
"permission_denied": "The control holder denied your request",
|
||||
"permission_not_granted": "Control request unsuccessful",
|
||||
"permission_connection_lost": "Connection lost. Request result is unconfirmed.",
|
||||
"permission_result_timeout": "No control confirmation received yet. Please retry later.",
|
||||
"permission_handover_pending": "Please handle the current control handover request first",
|
||||
"controlling": "Controlling",
|
||||
"not_controlling": "Not Controlling",
|
||||
"permission_request_title": "Permission Change",
|
||||
@@ -355,6 +376,30 @@
|
||||
"left_right": "Left/Right",
|
||||
"emergency_stop": "E-Stop",
|
||||
"emergency_stopping": "Stopping",
|
||||
"emergency_submitting": "Sending",
|
||||
"emergency_unknown": "Unknown",
|
||||
"emergency_inactive": "Not stopped",
|
||||
"emergency_status_unavailable": "No valid e-stop status received for this vehicle. Command unavailable.",
|
||||
"emergency_already_active": "This vehicle is already in e-stop. No duplicate command sent.",
|
||||
"emergency_already_released": "This vehicle is not in e-stop. No release command sent.",
|
||||
"emergency_retry": "Tap to retry",
|
||||
"emergency_request_sent": "E-stop request submitted. Device action is unconfirmed.",
|
||||
"emergency_release_sent": "E-stop release requested. Device action is unconfirmed.",
|
||||
"emergency_request_failed": "Request failed or action unconfirmed. Check the vehicle before retrying.",
|
||||
"emergency_request_rejected": "Request rejected. The displayed state has not changed. Please retry.",
|
||||
"emergency_release_action": "Release",
|
||||
"mower_last_operation": "Last action: {operation}\n(Release to center: no action)",
|
||||
"mower_operation_on": "On",
|
||||
"mower_operation_off": "Off",
|
||||
"mower_operation_none": "None",
|
||||
"emergency_missing_sn": "No vehicle SN selected. E-stop request was not sent.",
|
||||
"emergency_confirm_title": "Confirm emergency stop",
|
||||
"emergency_confirm_message": "Send an emergency-stop request to vehicle {sn}? Confirm to enter the stop state in this app.",
|
||||
"emergency_release_title": "Confirm e-stop release",
|
||||
"emergency_release_message": "Request e-stop release for vehicle {sn}? Check that people and the work area are safe before confirming.",
|
||||
"emergency_cancel": "Cancel",
|
||||
"emergency_confirm_stop": "Confirm stop",
|
||||
"emergency_confirm_release": "Confirm release",
|
||||
"perm_unknown_device": "Unknown device",
|
||||
"perm_unknown_platform": "Unknown platform",
|
||||
"permission_request_body": "{platform} is requesting control\n\nDevice ID: {deviceId}\n\nRelease control?",
|
||||
@@ -377,14 +422,15 @@
|
||||
"view_map": "Map",
|
||||
"emergency_stop": "E-Stop",
|
||||
"emergency_stopping": "Stopping",
|
||||
"sheet_mower_title": "Mower Lift",
|
||||
"sheet_mower_hint": "Left: raise · Right: lower · Release: stop",
|
||||
"sheet_mower_title": "Mower Switch",
|
||||
"sheet_mower_hint": "Left: on · Right: off · Release to center: no action",
|
||||
"sheet_chassis_title": "Chassis Lift",
|
||||
"sheet_chassis_hint": "Left: up · Right: down · Release: stop",
|
||||
"sheet_fire_title": "Ignition",
|
||||
"sheet_fire_hint": "Left: ignite · Right: extinguish · Center: stop",
|
||||
"seg_mower_up": "Raise",
|
||||
"seg_mower_down": "Lower",
|
||||
"seg_mower_up": "On",
|
||||
"seg_mower_down": "Off",
|
||||
"seg_mower_idle": "No action",
|
||||
"seg_chassis_up": "Up",
|
||||
"seg_chassis_down": "Down",
|
||||
"seg_fire_up": "Ignite",
|
||||
@@ -435,6 +481,14 @@
|
||||
"chassis_height": "Height",
|
||||
"position_quality": "Position Quality",
|
||||
"mower_status": "Mower",
|
||||
"mower_stopped": "Stopped",
|
||||
"left_measured_rpm": "Left measured",
|
||||
"right_measured_rpm": "Right measured",
|
||||
"left_target_rpm": "Left target",
|
||||
"right_target_rpm": "Right target",
|
||||
"status_moving": "Moving",
|
||||
"status_stopped": "Stopped",
|
||||
"status_blocked": "Blocked",
|
||||
"mower_running": "Running",
|
||||
"battery_label": "Battery",
|
||||
"current_speed": "Speed",
|
||||
@@ -784,6 +838,9 @@
|
||||
"view_detail": "View details",
|
||||
"stat_energy": "Energy",
|
||||
"stat_control_mode": "Control mode",
|
||||
"stat_emergency_stop": "E-stop status",
|
||||
"emergency_stop_active": "E-stop on",
|
||||
"emergency_stop_inactive": "E-stop off",
|
||||
"stat_chip_temp": "Chip temperature",
|
||||
"stat_blade_speed": "Blade speed",
|
||||
"stat_voltage": "Battery voltage",
|
||||
|
||||
@@ -336,6 +336,29 @@
|
||||
},
|
||||
|
||||
"remote_control": {
|
||||
"permission_checking": "查询中…",
|
||||
"permission_sending": "申请中…",
|
||||
"permission_waiting": "等待响应…",
|
||||
"permission_unconfirmed": "结果未确认",
|
||||
"permission_request_failed": "申请未成功",
|
||||
"permission_invalid_device": "无法申请:未获取到目标设备",
|
||||
"permission_auth_required": "登录信息失效,请重新登录",
|
||||
"permission_query_invalid": "权限查询返回异常,请重试",
|
||||
"permission_query_rejected": "权限查询未成功,请稍后重试",
|
||||
"permission_query_timeout": "权限查询超时,请重试",
|
||||
"permission_query_failed": "权限查询失败,请检查网络后重试",
|
||||
"permission_tcp_disconnected": "申请未发送:TCP 未连接",
|
||||
"permission_send_uncertain": "发送异常,未确认是否送达,请稍后重试",
|
||||
"permission_sent": "申请已通过 TCP 发出,等待响应",
|
||||
"permission_already_granted": "当前已拥有控制权",
|
||||
"permission_granted": "已获得控制权",
|
||||
"permission_denied": "对方拒绝了控制权申请",
|
||||
"permission_not_granted": "控制权申请未成功",
|
||||
"permission_connection_lost": "连接已断开,申请结果未确认",
|
||||
"permission_result_timeout": "暂未收到控制权确认,请稍后重试",
|
||||
"permission_handover_pending": "请先处理当前的权限交接请求",
|
||||
"tcp_heartbeat": "遥控心跳:收到服务器心跳时闪亮",
|
||||
"tcp_unavailable": "遥控连接暂不可用,请稍后重试",
|
||||
"controlling": "正在控制",
|
||||
"not_controlling": "未在控制",
|
||||
"permission_request_title": "权限变更",
|
||||
@@ -355,6 +378,30 @@
|
||||
"left_right": "左右控制",
|
||||
"emergency_stop": "急停",
|
||||
"emergency_stopping": "急停中",
|
||||
"emergency_submitting": "请求中",
|
||||
"emergency_unknown": "状态未知",
|
||||
"emergency_inactive": "未急停",
|
||||
"emergency_status_unavailable": "未收到该机器的有效急停状态,暂不能下发",
|
||||
"emergency_already_active": "当前车辆已处于急停状态,无需重复下发",
|
||||
"emergency_already_released": "当前车辆未急停,无需重复解除",
|
||||
"emergency_retry": "点击重试",
|
||||
"emergency_request_sent": "急停请求已提交,设备执行待确认",
|
||||
"emergency_release_sent": "解除急停请求已提交,设备执行待确认",
|
||||
"emergency_request_failed": "请求失败或执行结果未确认,请核对车辆状态后重试",
|
||||
"emergency_request_rejected": "操作失败,页面状态未切换,请重试",
|
||||
"emergency_release_action": "解除急停",
|
||||
"mower_last_operation": "上次操作:{operation}\n(松手回中不触发)",
|
||||
"mower_operation_on": "开启",
|
||||
"mower_operation_off": "关闭",
|
||||
"mower_operation_none": "无",
|
||||
"emergency_missing_sn": "未找到当前车辆 SN,急停请求未发送",
|
||||
"emergency_confirm_title": "确认急停",
|
||||
"emergency_confirm_message": "确定向车辆 {sn} 发送急停请求吗?确认后将进入急停操作状态。",
|
||||
"emergency_release_title": "确认解除急停",
|
||||
"emergency_release_message": "确定向车辆 {sn} 发送解除急停请求吗?请先确认周围人员和作业环境安全。",
|
||||
"emergency_cancel": "取消",
|
||||
"emergency_confirm_stop": "确认急停",
|
||||
"emergency_confirm_release": "确认解除",
|
||||
"perm_unknown_device": "未知设备",
|
||||
"perm_unknown_platform": "未知平台",
|
||||
"permission_request_body": "{platform} 端正在请求控制权\n\n设备ID: {deviceId}\n\n是否同意释放控制权?",
|
||||
@@ -377,14 +424,15 @@
|
||||
"view_map": "查看地图",
|
||||
"emergency_stop": "紧急停止",
|
||||
"emergency_stopping": "急停中",
|
||||
"sheet_mower_title": "割刀升降",
|
||||
"sheet_mower_hint": "左滑抬刀 · 右滑降刀 · 松手停",
|
||||
"sheet_mower_title": "割刀开关",
|
||||
"sheet_mower_hint": "左滑开启 · 右滑关闭 · 松手回中不触发",
|
||||
"sheet_chassis_title": "底盘升降",
|
||||
"sheet_chassis_hint": "左滑升 · 右滑降 · 松手停",
|
||||
"sheet_fire_title": "点火",
|
||||
"sheet_fire_hint": "左滑点火 · 右滑熄火 · 中间停",
|
||||
"seg_mower_up": "抬刀",
|
||||
"seg_mower_down": "降刀",
|
||||
"seg_mower_up": "开启",
|
||||
"seg_mower_down": "关闭",
|
||||
"seg_mower_idle": "不触发",
|
||||
"seg_chassis_up": "升高",
|
||||
"seg_chassis_down": "降低",
|
||||
"seg_fire_up": "点火",
|
||||
@@ -435,6 +483,14 @@
|
||||
"chassis_height": "底盘高度",
|
||||
"position_quality": "定位质量",
|
||||
"mower_status": "割刀状态",
|
||||
"mower_stopped": "已停转",
|
||||
"left_measured_rpm": "左轮实测",
|
||||
"right_measured_rpm": "右轮实测",
|
||||
"left_target_rpm": "左轮目标",
|
||||
"right_target_rpm": "右轮目标",
|
||||
"status_moving": "行驶中",
|
||||
"status_stopped": "已停止",
|
||||
"status_blocked": "受阻",
|
||||
"mower_running": "运行中",
|
||||
"battery_label": "电池电量",
|
||||
"current_speed": "当前速度",
|
||||
@@ -783,6 +839,9 @@
|
||||
"view_detail": "查看详情",
|
||||
"stat_energy": "能源",
|
||||
"stat_control_mode": "控制模式",
|
||||
"stat_emergency_stop": "急停状态",
|
||||
"emergency_stop_active": "急停中",
|
||||
"emergency_stop_inactive": "未急停",
|
||||
"stat_chip_temp": "芯片温度",
|
||||
"stat_blade_speed": "割刀转速",
|
||||
"stat_voltage": "电池电压",
|
||||
|
||||
@@ -280,6 +280,7 @@ class _DeviceStatusModalState extends State<DeviceStatusModal> {
|
||||
|
||||
Widget _buildOtherParamsTable(DeviceStatusUpdated state) {
|
||||
final status = state.status;
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -415,6 +416,25 @@ class _DeviceStatusModalState extends State<DeviceStatusModal> {
|
||||
),
|
||||
],
|
||||
),
|
||||
TableRow(
|
||||
children: [
|
||||
_buildTableCell(
|
||||
l10n.translate('device_detail_v2.stat_emergency_stop'),
|
||||
),
|
||||
_buildTableCell(
|
||||
status.emergencyStop == null
|
||||
? '--'
|
||||
: l10n.translate(
|
||||
status.emergencyStop!
|
||||
? 'device_detail_v2.emergency_stop_active'
|
||||
: 'device_detail_v2.emergency_stop_inactive',
|
||||
),
|
||||
textColor: status.emergencyStop == true
|
||||
? const Color(0xFFDC2626)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
TableRow(
|
||||
children: [
|
||||
_buildTableCell(
|
||||
@@ -443,7 +463,11 @@ class _DeviceStatusModalState extends State<DeviceStatusModal> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTableCell(String text, {bool isHeader = false}) {
|
||||
Widget _buildTableCell(
|
||||
String text, {
|
||||
bool isHeader = false,
|
||||
Color? textColor,
|
||||
}) {
|
||||
return TableCell(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 6),
|
||||
@@ -452,7 +476,8 @@ class _DeviceStatusModalState extends State<DeviceStatusModal> {
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: isHeader ? const Color(0xFF333333) : const Color(0xFF666666),
|
||||
color: textColor ??
|
||||
(isHeader ? const Color(0xFF333333) : const Color(0xFF666666)),
|
||||
fontWeight: isHeader ? FontWeight.bold : FontWeight.normal,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -59,6 +59,9 @@ class HttpApiConsts {
|
||||
// GET,2=自主任务,3=远程遥控;路径 modeChage 沿用后端协议拼写。
|
||||
static String get hostModeChange => "$baseUrl/iot/host/modeChage";
|
||||
|
||||
// GET,query: deviceId、eStop(1=请求急停,0=请求解除)。
|
||||
static String get hostEmergencyStopChange => "$baseUrl/iot/host/eStopChange";
|
||||
|
||||
// 修改设备别名(只写 deviceAlias,deviceName 保持不变)
|
||||
static String get updateDeviceAlias =>
|
||||
"$baseUrl/forward/device/updateDeviceAlias";
|
||||
|
||||
@@ -45,6 +45,10 @@ import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remot
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../features/auth/data/datasources/auth_http_datasource.dart';
|
||||
@@ -390,6 +394,17 @@ Future<void> init() async {
|
||||
() => RequestControlPermissionUseCase(sl()),
|
||||
);
|
||||
|
||||
// 独立急停接口:仅注册数据/领域层,不自动请求或接入页面。
|
||||
sl.registerLazySingleton(() => EmergencyStopRemoteDatasource(sl<Dio>()));
|
||||
sl.registerLazySingleton<DeviceEmergencyStopRepository>(
|
||||
() =>
|
||||
DeviceEmergencyStopRepositoryImpl(sl<EmergencyStopRemoteDatasource>()),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() =>
|
||||
RequestDeviceEmergencyStopUseCase(sl<DeviceEmergencyStopRepository>()),
|
||||
);
|
||||
|
||||
/// Home V2
|
||||
sl.registerLazySingleton<HomeRemoteDataSource>(
|
||||
() => HomeRemoteDataSourceImpl(),
|
||||
@@ -574,6 +589,7 @@ Future<void> init() async {
|
||||
sl<TcpClient>(), // TcpClient
|
||||
sl(), // NetMessageDispatcher
|
||||
sl(), // DeviceStatusBloc
|
||||
requestEmergencyStop: sl<RequestDeviceEmergencyStopUseCase>(),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
47
lib/core/logging/control_permission_diagnostics.dart
Normal file
47
lib/core/logging/control_permission_diagnostics.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'remote_control_diagnostics.dart';
|
||||
|
||||
/// Passive tracing only. Identifiers stay local and never enter HTTP/TCP data.
|
||||
class ControlPermissionDiagnostics {
|
||||
static final Object _scopeKey = Object();
|
||||
|
||||
static Map<String, Object?>? get context =>
|
||||
Zone.current[_scopeKey] as Map<String, Object?>?;
|
||||
|
||||
static T scope<T>(Map<String, Object?> fields, T Function() action) =>
|
||||
runZoned(
|
||||
action,
|
||||
zoneValues: {_scopeKey: Map<String, Object?>.of(fields)},
|
||||
);
|
||||
|
||||
static Object? scalar(Object? value) =>
|
||||
value == null || value is String || value is num || value is bool
|
||||
? value
|
||||
: '<${value.runtimeType}>';
|
||||
|
||||
/// Callers supply whitelisted fields, never tokens, headers, or raw packets.
|
||||
static void event(String step, [Map<String, Object?> fields = const {}]) {
|
||||
try {
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final record = <String, Object?>{
|
||||
'time': DateTime.now().toIso8601String(),
|
||||
...?context,
|
||||
...fields,
|
||||
'traceVersion': 1,
|
||||
'permissionStep': step,
|
||||
};
|
||||
final startedUs = record['startedUs'];
|
||||
if (startedUs is int) {
|
||||
record['elapsedMs'] = (trace.elapsedUs - startedUs) ~/ 1000;
|
||||
}
|
||||
trace.event('permission_trace', record);
|
||||
debugPrint('[权限链][$step] ${jsonEncode(record)}');
|
||||
} catch (_) {
|
||||
// Logging cannot interrupt permission, motion, or safety handling.
|
||||
}
|
||||
}
|
||||
}
|
||||
121
lib/core/logging/remote_control_diagnostics.dart
Normal file
121
lib/core/logging/remote_control_diagnostics.dart
Normal file
@@ -0,0 +1,121 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// Passive motion tracing. This class never sends commands or awaits a network
|
||||
/// operation. File writes are buffered and serialized separately from control.
|
||||
class RemoteControlDiagnostics {
|
||||
RemoteControlDiagnostics({Future<void> Function(String)? append})
|
||||
: _appendOverride = append;
|
||||
|
||||
static RemoteControlDiagnostics instance = RemoteControlDiagnostics();
|
||||
static final Object _frameKey = Object();
|
||||
final Future<void> Function(String)? _appendOverride;
|
||||
final Stopwatch _clock = Stopwatch()..start();
|
||||
final String _run = DateTime.now().microsecondsSinceEpoch.toString();
|
||||
final List<String> _pending = [];
|
||||
Future<Directory>? _directory;
|
||||
Future<void>? _inFlight;
|
||||
Timer? _flushTimer;
|
||||
int _sequence = 0;
|
||||
int _frameSequence = 0;
|
||||
int _sessionSequence = 0;
|
||||
int _dropped = 0;
|
||||
String? activeDevice;
|
||||
|
||||
int get elapsedUs => _clock.elapsedMicroseconds;
|
||||
|
||||
void begin(String? device, Map<String, Object?> configuration) {
|
||||
activeDevice = device;
|
||||
_sessionSequence++;
|
||||
event('session_start', configuration);
|
||||
}
|
||||
|
||||
void end(String reason) {
|
||||
event('session_end', {'reason': reason});
|
||||
activeDevice = null;
|
||||
unawaited(flush());
|
||||
}
|
||||
|
||||
/// Local correlation only; no identifiers are added to the wire protocol.
|
||||
T frame<T>(String source, Map<String, Object?> fields, T Function() send) {
|
||||
final context = <String, Object?>{
|
||||
'session': _sessionSequence,
|
||||
'device': activeDevice,
|
||||
'frame': ++_frameSequence,
|
||||
'source': source,
|
||||
...fields,
|
||||
};
|
||||
return runZoned(send, zoneValues: {_frameKey: context});
|
||||
}
|
||||
|
||||
void event(String stage, Map<String, Object?> fields) {
|
||||
try {
|
||||
final frame = Zone.current[_frameKey] as Map<String, Object?>?;
|
||||
final record = <String, Object?>{
|
||||
'time': DateTime.now().toIso8601String(),
|
||||
'us': elapsedUs,
|
||||
'run': _run,
|
||||
'session': _sessionSequence,
|
||||
'seq': ++_sequence,
|
||||
'device': activeDevice,
|
||||
if (frame != null) ...frame,
|
||||
'stage': stage,
|
||||
...fields,
|
||||
};
|
||||
for (final key in record.keys.toList()) {
|
||||
final value = record[key];
|
||||
if (value is double && !value.isFinite) record[key] = value.toString();
|
||||
}
|
||||
// A stalled filesystem cannot grow memory without bounds or block control.
|
||||
if (_pending.length >= 2000) {
|
||||
_pending.removeAt(0);
|
||||
_dropped++;
|
||||
}
|
||||
_pending.add('${jsonEncode(record)}\n');
|
||||
_flushTimer ??= Timer(const Duration(milliseconds: 500), () {
|
||||
_flushTimer = null;
|
||||
unawaited(flush());
|
||||
});
|
||||
} catch (_) {
|
||||
// Diagnostics must never interrupt an input, control or safety callback.
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _append(String content) async {
|
||||
final override = _appendOverride;
|
||||
if (override != null) return override(content);
|
||||
final directory = await (_directory ??= getApplicationDocumentsDirectory());
|
||||
final day = DateTime.now().toIso8601String().substring(0, 10);
|
||||
await File(
|
||||
'${directory.path}/remote_control_$day.jsonl',
|
||||
).writeAsString(content, mode: FileMode.append);
|
||||
}
|
||||
|
||||
Future<void> flush() {
|
||||
_flushTimer?.cancel();
|
||||
_flushTimer = null;
|
||||
return _inFlight ??= _drain().whenComplete(() => _inFlight = null);
|
||||
}
|
||||
|
||||
Future<void> _drain() async {
|
||||
while (_pending.isNotEmpty) {
|
||||
final dropped = _dropped;
|
||||
_dropped = 0;
|
||||
final batch = _pending.join();
|
||||
_pending.clear();
|
||||
try {
|
||||
await _append(
|
||||
'${dropped == 0 ? '' : '${jsonEncode({'stage': 'diagnostic_overflow', 'dropped': dropped})}\n'}$batch',
|
||||
);
|
||||
} catch (_) {
|
||||
// Mark missing records in the next successful write instead of silently
|
||||
// making a logging failure look like a gap in TCP transmission.
|
||||
_dropped += dropped + '\n'.allMatches(batch).length;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,35 +99,37 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
controller = StreamController(
|
||||
onListen: () {
|
||||
// 先监听报文再订阅 Topic,接住订阅时立即到达的消息。
|
||||
messageSubscription = messages.where((msg) => msg.topic == topic).listen(
|
||||
(message) {
|
||||
try {
|
||||
final json = jsonDecode(message.payload);
|
||||
if (json is! Map) return;
|
||||
final payload = json['data'];
|
||||
final data = payload is Map ? payload : json;
|
||||
final battery = HostRealtimeMessageEntity.parseBatteryPercentage(
|
||||
data['battery_percentage'],
|
||||
);
|
||||
lastBattery = battery ?? lastBattery;
|
||||
controller.add(
|
||||
(
|
||||
battery: lastBattery,
|
||||
controlMode: data['control_mode']?.toString().trim() ?? '',
|
||||
),
|
||||
);
|
||||
} on FormatException {
|
||||
// 忽略格式异常的单帧,等待下一次上报。
|
||||
}
|
||||
},
|
||||
onError: controller.addError,
|
||||
onDone: controller.close,
|
||||
);
|
||||
topicSubscription = mqttClient.subscribe(topic).catchError(
|
||||
(Object error, StackTrace stackTrace) {
|
||||
if (!controller.isClosed) controller.addError(error, stackTrace);
|
||||
},
|
||||
);
|
||||
messageSubscription = messages
|
||||
.where((msg) => msg.topic == topic)
|
||||
.listen(
|
||||
(message) {
|
||||
try {
|
||||
final json = jsonDecode(message.payload);
|
||||
if (json is! Map) return;
|
||||
final payload = json['data'];
|
||||
final data = payload is Map ? payload : json;
|
||||
final battery =
|
||||
HostRealtimeMessageEntity.parseBatteryPercentage(
|
||||
data['battery_percentage'],
|
||||
);
|
||||
lastBattery = battery ?? lastBattery;
|
||||
controller.add((
|
||||
battery: lastBattery,
|
||||
controlMode: data['control_mode']?.toString().trim() ?? '',
|
||||
));
|
||||
} on FormatException {
|
||||
// 忽略格式异常的单帧,等待下一次上报。
|
||||
}
|
||||
},
|
||||
onError: controller.addError,
|
||||
onDone: controller.close,
|
||||
);
|
||||
topicSubscription = mqttClient.subscribe(topic).catchError((
|
||||
Object error,
|
||||
StackTrace stackTrace,
|
||||
) {
|
||||
if (!controller.isClosed) controller.addError(error, stackTrace);
|
||||
});
|
||||
},
|
||||
onCancel: () async {
|
||||
await messageSubscription?.cancel();
|
||||
@@ -154,7 +156,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
|
||||
// 🔥 同一设备重复调用:去重,不重复订阅(参照 DroneOsdDataSource 已验证的模式)
|
||||
if (_deviceSn == deviceSn && _subscription != null) {
|
||||
debugPrint('${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} [MowerRealtimeDataSource] 已在监听该设备,跳过: $deviceSn',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -164,7 +168,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
|
||||
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
|
||||
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
|
||||
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 已退订旧设备: $_deviceSn',
|
||||
);
|
||||
}
|
||||
|
||||
_deviceSn = deviceSn;
|
||||
@@ -173,15 +179,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
_routeMsgCount = 0;
|
||||
_hostMsgCount = 0;
|
||||
|
||||
// 先监听消息,接住订阅后立即到达的推送(包括 retained 消息)。
|
||||
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
|
||||
|
||||
await mqttClient.subscribe(_realtimeTopic(deviceSn));
|
||||
await mqttClient.subscribe(_locationTopic(deviceSn));
|
||||
await mqttClient.subscribe(_routeTopic(deviceSn));
|
||||
await mqttClient.subscribe(_hostRealtimeTopic(deviceSn));
|
||||
|
||||
// 消息流监听只建立一次,按 _deviceSn 过滤
|
||||
_subscription ??= mqttClient.messageStream?.listen(_handleMessage);
|
||||
|
||||
debugPrint('${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} ✅ [MowerRealtimeDataSource] 开始监听设备: $deviceSn',
|
||||
);
|
||||
debugPrint(' 车辆实时: ${_realtimeTopic(deviceSn)}');
|
||||
debugPrint(' 定位: ${_locationTopic(deviceSn)}');
|
||||
debugPrint(' 路径规划: ${_routeTopic(deviceSn)}');
|
||||
@@ -196,7 +204,9 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
await mqttClient.unsubscribe(_locationTopic(_deviceSn!));
|
||||
await mqttClient.unsubscribe(_routeTopic(_deviceSn!));
|
||||
await mqttClient.unsubscribe(_hostRealtimeTopic(_deviceSn!));
|
||||
debugPrint('${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🔕 [MowerRealtimeDataSource] 停止监听设备: $_deviceSn',
|
||||
);
|
||||
_deviceSn = null;
|
||||
}
|
||||
|
||||
@@ -206,12 +216,17 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
|
||||
// 🔥 防串台:只处理当前监听设备的主题(mower/ 和 device/ 前缀都要匹配)
|
||||
if (!message.topic.contains('mower/$sn/') &&
|
||||
!message.topic.contains('device/$sn/')) return;
|
||||
!message.topic.contains('device/$sn/'))
|
||||
return;
|
||||
|
||||
// 🔥 第一阶段:打印原始报文,确认格式后再完善解析
|
||||
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] ──────── 收到消息 ────────');
|
||||
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
|
||||
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] payload: ${message.payload}');
|
||||
// 实时状态逐帧打印原始报文,在解析前确认急停字段是否实际下发。
|
||||
if (message.topic == _realtimeTopic(sn) ||
|
||||
message.topic == _hostRealtimeTopic(sn)) {
|
||||
debugPrint('${LogTime.now()} 📥 [MQTT-机器状态] topic: ${message.topic}');
|
||||
debugPrint('[MQTT-机器状态] payload 开始');
|
||||
debugPrint(message.payload, wrapWidth: 800);
|
||||
debugPrint('[MQTT-机器状态] payload 结束');
|
||||
}
|
||||
|
||||
try {
|
||||
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
|
||||
@@ -224,9 +239,13 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
if (_vehicleMsgCount == 1) {
|
||||
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 车辆实时首帧到达: $sn');
|
||||
}
|
||||
debugPrint('${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 📊 [MQTT-机器状态] 车辆实时第$_vehicleMsgCount帧 解析后: type=${vehicle.type}, 数据点=${vehicle.data.length}个',
|
||||
);
|
||||
for (final dp in vehicle.data) {
|
||||
debugPrint('${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}');
|
||||
debugPrint(
|
||||
'${LogTime.now()} ├ ${dp.name} = ${dp.value}${dp.unit}',
|
||||
);
|
||||
}
|
||||
_vehicleController.add(vehicle);
|
||||
}
|
||||
@@ -238,7 +257,7 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
// 🔥 关键修复:坐标在 data 子对象中,不是顶层
|
||||
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
|
||||
final location = MowerLocationEntity.fromJson(dataObj);
|
||||
debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}');
|
||||
// debugPrint('${LogTime.now()} 📍 [MQTT-机器状态] 定位第$_locationMsgCount帧 解析后: lat=${location.latitude}, lng=${location.longitude}, alt=${location.altitude}, heading=${location.heading}, speed=${location.speed}');
|
||||
_locationController.add(location);
|
||||
} else if (message.topic.endsWith(_hostRealtimeSuffix)) {
|
||||
// 🔥 主机实时(新增话题,纯附加):外层套信封,数据在 json.data,提取方式与定位一致
|
||||
@@ -247,8 +266,14 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
debugPrint('${LogTime.now()} 🎉 [MQTT-主机实时] 首帧到达: $sn');
|
||||
}
|
||||
final dataObj = jsonData['data'] as Map<String, dynamic>? ?? jsonData;
|
||||
final host = HostRealtimeMessageEntity.fromJson(dataObj);
|
||||
debugPrint('${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} 急停=${host.emergencyStop} 运动=${host.motion}');
|
||||
final host = HostRealtimeMessageEntity.fromJson(
|
||||
dataObj,
|
||||
deviceSn: sn,
|
||||
receivedAt: message.timestamp,
|
||||
);
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🛰️ [MQTT-主机实时] 第$_hostMsgCount帧 电量=${host.batteryPercentage}% 电压=${host.batteryVoltage}V 控制模式=${host.controlMode} emergency_stop存在=${dataObj.containsKey('emergency_stop')} 原始值=${dataObj['emergency_stop']} 急停解析值=${host.emergencyStop} 运动=${host.motion}',
|
||||
);
|
||||
_hostRealtimeController.add(host);
|
||||
} else if (message.topic.endsWith(_routeSuffix)) {
|
||||
_routeMsgCount++;
|
||||
@@ -256,11 +281,15 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
debugPrint('${LogTime.now()} 🎉 [MQTT-机器状态] 路径规划首帧到达: $sn');
|
||||
}
|
||||
final routeMsg = RouteStatusEntity.fromJson(jsonData);
|
||||
debugPrint('${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}');
|
||||
debugPrint(
|
||||
'${LogTime.now()} 🛤️ [MQTT-机器状态] 路径规划第$_routeMsgCount帧 - 设备: ${routeMsg.deviceId}, 任务: ${routeMsg.taskId}, 点数: ${routeMsg.data.length}',
|
||||
);
|
||||
_routeController.add(routeMsg);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败: $e');
|
||||
debugPrint(
|
||||
'${LogTime.now()} ❌ [MowerRealtimeDataSource] 解析消息失败 topic=${message.topic}: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import 'package:equatable/equatable.dart';
|
||||
/// 报文外层套一层信封,真正数据在 `data` 子对象(由 DataSource 提取后传入)。
|
||||
/// 字段与后端 Java 实体一一对应,采用防御式解析,缺字段用默认值兜底。
|
||||
class HostRealtimeMessageEntity extends Equatable {
|
||||
final String? deviceSn;
|
||||
final DateTime? receivedAt;
|
||||
final double batteryPercentage; // 实时电量百分比
|
||||
final double batteryVoltage; // 实时电压
|
||||
final double leftMotorCurrent; // 实时左电机电流
|
||||
@@ -19,7 +21,7 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
final double totalWorkDuration; // 累计作业时长
|
||||
final double totalWorkDistance; // 累计作业里程
|
||||
final String motion; // moving|stopped|blocked 运动状态
|
||||
final bool emergencyStop; // 急停状态
|
||||
final bool? emergencyStop; // 急停状态;null 表示未上报或值无效
|
||||
final double leftTargetRpm; // 实时左电机目标转速
|
||||
final double rightTargetRpm; // 实时右电机目标转速
|
||||
final double leftMeasuredRpm; // 实时左电机测量转速
|
||||
@@ -35,6 +37,8 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
final Map<String, dynamic> rawData;
|
||||
|
||||
const HostRealtimeMessageEntity({
|
||||
this.deviceSn,
|
||||
this.receivedAt,
|
||||
this.batteryPercentage = 0,
|
||||
this.batteryVoltage = 0,
|
||||
this.leftMotorCurrent = 0,
|
||||
@@ -49,7 +53,7 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
this.totalWorkDuration = 0,
|
||||
this.totalWorkDistance = 0,
|
||||
this.motion = '',
|
||||
this.emergencyStop = false,
|
||||
this.emergencyStop,
|
||||
this.leftTargetRpm = 0,
|
||||
this.rightTargetRpm = 0,
|
||||
this.leftMeasuredRpm = 0,
|
||||
@@ -64,9 +68,16 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
});
|
||||
|
||||
/// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致)
|
||||
factory HostRealtimeMessageEntity.fromJson(Map<String, dynamic> data) {
|
||||
factory HostRealtimeMessageEntity.fromJson(
|
||||
Map<String, dynamic> data, {
|
||||
String? deviceSn,
|
||||
DateTime? receivedAt,
|
||||
}) {
|
||||
return HostRealtimeMessageEntity(
|
||||
batteryPercentage: parseBatteryPercentage(data['battery_percentage']) ?? 0,
|
||||
deviceSn: deviceSn,
|
||||
receivedAt: receivedAt,
|
||||
batteryPercentage:
|
||||
parseBatteryPercentage(data['battery_percentage']) ?? 0,
|
||||
batteryVoltage: _toDouble(data['battery_voltage']),
|
||||
leftMotorCurrent: _toDouble(data['left_motor_current']),
|
||||
rightMotorCurrent: _toDouble(data['right_motor_current']),
|
||||
@@ -115,40 +126,43 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
return double.tryParse(value.toString()) ?? 0;
|
||||
}
|
||||
|
||||
static bool _toBool(dynamic value) {
|
||||
if (value == null) return false;
|
||||
static bool? _toBool(dynamic value) {
|
||||
if (value is bool) return value;
|
||||
if (value is num) return value != 0;
|
||||
final s = value.toString().toLowerCase();
|
||||
return s == 'true' || s == '1';
|
||||
if (value == 1) return true;
|
||||
if (value == 0) return false;
|
||||
final s = value?.toString().trim().toLowerCase();
|
||||
if (s == 'true' || s == '1') return true;
|
||||
if (s == 'false' || s == '0') return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
batteryPercentage,
|
||||
batteryVoltage,
|
||||
leftMotorCurrent,
|
||||
rightMotorCurrent,
|
||||
leftMotorTemperature,
|
||||
rightMotorTemperature,
|
||||
mainTemperature,
|
||||
yaw,
|
||||
pitch,
|
||||
headingStatus,
|
||||
totalWorkArea,
|
||||
totalWorkDuration,
|
||||
totalWorkDistance,
|
||||
motion,
|
||||
emergencyStop,
|
||||
leftTargetRpm,
|
||||
rightTargetRpm,
|
||||
leftMeasuredRpm,
|
||||
rightMeasuredRpm,
|
||||
leftMotorRpm,
|
||||
rightMotorRpm,
|
||||
roll,
|
||||
controlMode,
|
||||
linearSpeed,
|
||||
angularSpeed,
|
||||
];
|
||||
batteryPercentage,
|
||||
batteryVoltage,
|
||||
leftMotorCurrent,
|
||||
rightMotorCurrent,
|
||||
leftMotorTemperature,
|
||||
rightMotorTemperature,
|
||||
mainTemperature,
|
||||
yaw,
|
||||
pitch,
|
||||
headingStatus,
|
||||
totalWorkArea,
|
||||
totalWorkDuration,
|
||||
totalWorkDistance,
|
||||
motion,
|
||||
emergencyStop,
|
||||
leftTargetRpm,
|
||||
rightTargetRpm,
|
||||
leftMeasuredRpm,
|
||||
rightMeasuredRpm,
|
||||
leftMotorRpm,
|
||||
rightMotorRpm,
|
||||
roll,
|
||||
controlMode,
|
||||
linearSpeed,
|
||||
angularSpeed,
|
||||
rawData,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ class DeviceDataPoint extends Equatable {
|
||||
factory DeviceDataPoint.fromJson(Map<String, dynamic> json) {
|
||||
return DeviceDataPoint(
|
||||
name: json['name'] as String? ?? '',
|
||||
value: json['value'] as String? ?? '',
|
||||
value: json['value']?.toString() ?? '',
|
||||
unit: json['unit'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
97
lib/core/network/tcp/control_frame_scheduler.dart
Normal file
97
lib/core/network/tcp/control_frame_scheduler.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// One shared 0x00 sender. There is no FIFO of old movement commands: only
|
||||
/// the latest normal command and one priority stop/emergency may be pending.
|
||||
class ControlFrameScheduler {
|
||||
ControlFrameScheduler({int Function()? nowUs}) : _nowUs = nowUs {
|
||||
_clock.start();
|
||||
}
|
||||
|
||||
/// Shared interval for both the control loop and the transport gate.
|
||||
static const interval = Duration(milliseconds: 250);
|
||||
final Stopwatch _clock = Stopwatch();
|
||||
final int Function()? _nowUs;
|
||||
Timer? _timer;
|
||||
_ControlWrite? _priority;
|
||||
_ControlWrite? _latest;
|
||||
int? _lastCompletedUs;
|
||||
bool _writing = false;
|
||||
|
||||
int get _now => _nowUs?.call() ?? _clock.elapsedMicroseconds;
|
||||
|
||||
Future<bool> submit(
|
||||
Future<bool> Function() write, {
|
||||
required bool priority,
|
||||
required bool Function() isCurrent,
|
||||
}) {
|
||||
// Preserve each request's diagnostic Zone even when a later request replaces
|
||||
// the one that originally scheduled the timer.
|
||||
final job = _ControlWrite(Zone.current.bindCallback(write), isCurrent);
|
||||
if (priority) {
|
||||
_latest?.complete(false);
|
||||
_latest = null;
|
||||
_priority?.complete(false);
|
||||
_priority = job;
|
||||
} else {
|
||||
_latest?.complete(false);
|
||||
_latest = job;
|
||||
}
|
||||
_pump();
|
||||
return job.result.future;
|
||||
}
|
||||
|
||||
void _pump() {
|
||||
if (_writing || _timer != null) return;
|
||||
final job = _priority ?? _latest;
|
||||
if (job == null) return;
|
||||
if (!job.isCurrent()) {
|
||||
_remove(job);
|
||||
job.complete(false);
|
||||
_pump();
|
||||
return;
|
||||
}
|
||||
final remaining = _lastCompletedUs == null
|
||||
? 0
|
||||
: interval.inMicroseconds - (_now - _lastCompletedUs!);
|
||||
if (remaining > 0) {
|
||||
_timer = Timer(Duration(microseconds: remaining), () {
|
||||
_timer = null;
|
||||
_pump(); // Recheck the monotonic clock; never send an early timer tick.
|
||||
});
|
||||
return;
|
||||
}
|
||||
_remove(job);
|
||||
_writing = true;
|
||||
unawaited(_write(job));
|
||||
}
|
||||
|
||||
void _remove(_ControlWrite job) {
|
||||
if (identical(_priority, job)) _priority = null;
|
||||
if (identical(_latest, job)) _latest = null;
|
||||
}
|
||||
|
||||
Future<void> _write(_ControlWrite job) async {
|
||||
try {
|
||||
job.complete(job.isCurrent() ? await job.write() : false);
|
||||
} catch (_) {
|
||||
job.complete(false);
|
||||
} finally {
|
||||
// Measuring after local flush completion is conservative: actual socket
|
||||
// additions are at least one interval apart, including priority frames.
|
||||
_lastCompletedUs = _now;
|
||||
_writing = false;
|
||||
_pump();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ControlWrite {
|
||||
_ControlWrite(this.write, this.isCurrent);
|
||||
final Future<bool> Function() write;
|
||||
final bool Function() isCurrent;
|
||||
final Completer<bool> result = Completer<bool>();
|
||||
|
||||
void complete(bool value) {
|
||||
if (!result.isCompleted) result.complete(value);
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,57 @@ import '../../../features/devices/domain/entities/running_status_entity.dart';
|
||||
import '../../../features/devices/domain/usecases/get_user_device_usecase.dart';
|
||||
import '../../../features/devices/domain/usecases/switch_device_usecase.dart';
|
||||
import '../../logging/i_logger_service.dart';
|
||||
import '../../logging/control_permission_diagnostics.dart';
|
||||
import '../../logging/remote_control_diagnostics.dart';
|
||||
import '../../storage/user_storage.dart';
|
||||
import '../protocol_decoder.dart';
|
||||
import 'tcp_status_cubit.dart';
|
||||
import 'control_frame_scheduler.dart';
|
||||
|
||||
class TcpClient {
|
||||
Socket? _socket;
|
||||
int _diagnosticPendingFlushes = 0;
|
||||
int? _diagnosticLastMotionAddUs;
|
||||
final ControlFrameScheduler _controlFrames = ControlFrameScheduler();
|
||||
final Set<Future<dynamic>> _pendingSocketFlushes = {};
|
||||
Future<dynamic>? _lastRawFlush;
|
||||
|
||||
/// Observe completion without awaiting, delaying or changing any sender.
|
||||
void _observeDiagnosticFlush(
|
||||
Future<dynamic> pending,
|
||||
int command,
|
||||
int beganUs,
|
||||
) {
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final connection = _connectionId;
|
||||
_pendingSocketFlushes.add(pending);
|
||||
_diagnosticPendingFlushes++;
|
||||
pending.then<void>(
|
||||
(_) {
|
||||
_diagnosticPendingFlushes--;
|
||||
_pendingSocketFlushes.remove(pending);
|
||||
trace.event('socket_flush_complete', {
|
||||
'cmd': command,
|
||||
'connection': connection,
|
||||
'durationUs': trace.elapsedUs - beganUs,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
},
|
||||
onError: (Object error, StackTrace stack) {
|
||||
_diagnosticPendingFlushes--;
|
||||
_pendingSocketFlushes.remove(pending);
|
||||
trace.event('socket_flush_error', {
|
||||
'cmd': command,
|
||||
'connection': connection,
|
||||
'durationUs': trace.elapsedUs - beganUs,
|
||||
'errorType': error.runtimeType.toString(),
|
||||
'error': error.toString(),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final _decoder = ProtocolDecoder();
|
||||
// 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听
|
||||
final _controller = StreamController<RawPacket>.broadcast();
|
||||
@@ -47,8 +92,10 @@ class TcpClient {
|
||||
static const int _maxReconnectFlaps = 5; // 🔥 最大允许连续成功-断开次数
|
||||
/// 🔥 重连耗尽回调:连续4次重连失败(含心跳超时)后触发,通知上层弹窗提示用户
|
||||
VoidCallback? onReconnectExhausted;
|
||||
|
||||
/// 🔥 重连开始回调:显示"TCP重连中"提示
|
||||
VoidCallback? onReconnectStarted;
|
||||
|
||||
/// 🔥 重连成功回调:显示"连接成功"提示
|
||||
VoidCallback? onReconnectSuccess;
|
||||
static const Duration _heartbeatTimeout = Duration(seconds: 15); // 心跳超时时间
|
||||
@@ -57,7 +104,8 @@ class TcpClient {
|
||||
int? _lastPort;
|
||||
bool isUserSwitch = false; // 用户是否切换设备
|
||||
bool _isSwitching = false;
|
||||
bool _connecting = false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争)
|
||||
bool _connecting =
|
||||
false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争)
|
||||
Completer<void>? _connectionCompleter; // 🔥 用于通知连接就绪
|
||||
int _connectionId = 0; // 🔥 连接代数:每次新建连接递增,旧socket回调发现ID不匹配则忽略
|
||||
|
||||
@@ -92,7 +140,9 @@ class TcpClient {
|
||||
final isRecent = elapsed.inSeconds < 2;
|
||||
|
||||
if (isRecent) {
|
||||
debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)');
|
||||
debugPrint(
|
||||
'🔍 [TCP] 距离上次认证 ${elapsed.inMilliseconds}ms (<2s),判定为自身认证触发(服务端残留 session)',
|
||||
);
|
||||
} else {
|
||||
debugPrint('🔍 [TCP] 距离上次认证 ${elapsed.inSeconds}s (>=2s),判定为真正的异地登录');
|
||||
}
|
||||
@@ -278,12 +328,19 @@ class TcpClient {
|
||||
// 必须在 _controller.add 之前检查,否则 AuthCubit 会判定为异地登录弹出退出弹窗
|
||||
if (packet.command == 0x12 && wasReconnecting) {
|
||||
try {
|
||||
final payloadStr = utf8.decode(packet.payload.length > 2
|
||||
? packet.payload.sublist(0, packet.payload.length - 2)
|
||||
: packet.payload);
|
||||
final payloadStr = utf8.decode(
|
||||
packet.payload.length > 2
|
||||
? packet.payload.sublist(0, packet.payload.length - 2)
|
||||
: packet.payload,
|
||||
);
|
||||
if (payloadStr.contains('have_logged_in')) {
|
||||
debugPrint('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session');
|
||||
_logger.logWithLevel('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连', shouldLog: true);
|
||||
debugPrint(
|
||||
'🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
_handleReconnectSessionReset(myConnId);
|
||||
return; // 停止处理后续数据,不分发给任何监听器
|
||||
}
|
||||
@@ -325,8 +382,13 @@ class TcpClient {
|
||||
onDone: () {
|
||||
// 🔥 关键修复:检查 connectionId,防止旧socket的回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
@@ -337,7 +399,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
@@ -385,7 +449,10 @@ class TcpClient {
|
||||
void _handleDisconnect() {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效,防止onDone/onError污染新连接
|
||||
debugPrint('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🔌 [TCP] _handleDisconnect, connectionId→$_connectionId',
|
||||
shouldLog: true,
|
||||
);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
@@ -394,7 +461,10 @@ class TcpClient {
|
||||
debugPrint('📊 [TCP] 连接断开次数: $_reconnectFlapCount/$_maxReconnectFlaps');
|
||||
if (_reconnectFlapCount >= _maxReconnectFlaps) {
|
||||
debugPrint('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🛑 [TCP] 连续 $_maxReconnectFlaps 次连上后立刻断开,停止重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
@@ -416,7 +486,10 @@ class TcpClient {
|
||||
// 🔥 限制总重连次数,防止网络不可达时无限重连
|
||||
if (_reconnectAttempt >= _maxReconnectAttempts) {
|
||||
debugPrint('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🛑 [TCP] 自动重连已达最大次数 $_maxReconnectAttempts 次,停止重连',
|
||||
shouldLog: true,
|
||||
);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
@@ -424,7 +497,9 @@ class TcpClient {
|
||||
// 🔥 重连退避:5s → 10s → 20s → 30s(max)
|
||||
final delay = [5, 10, 20, 30][_reconnectAttempt.clamp(0, 3)];
|
||||
_reconnectAttempt++;
|
||||
_logger.logWithLevel('⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}');
|
||||
_logger.logWithLevel(
|
||||
'⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}',
|
||||
);
|
||||
if (_lastHost == null || _lastPort == null) {
|
||||
_logger.logWithLevel('❌ 无法重连:Host 或 Port 为空!', shouldLog: true);
|
||||
return;
|
||||
@@ -446,32 +521,54 @@ class TcpClient {
|
||||
// 🔥 显示"TCP重连中"提示
|
||||
onReconnectStarted?.call();
|
||||
final reconnectStart = DateTime.now();
|
||||
final timeStr = '${reconnectStart.hour.toString().padLeft(2,'0')}:${reconnectStart.minute.toString().padLeft(2,'0')}:${reconnectStart.second.toString().padLeft(2,'0')}.${reconnectStart.millisecond.toString().padLeft(3,'0')}';
|
||||
final timeStr =
|
||||
'${reconnectStart.hour.toString().padLeft(2, '0')}:${reconnectStart.minute.toString().padLeft(2, '0')}:${reconnectStart.second.toString().padLeft(2, '0')}.${reconnectStart.millisecond.toString().padLeft(3, '0')}';
|
||||
debugPrint('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)');
|
||||
_logger.logWithLevel('⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏰ [TCP-重连] $timeStr 开始重连(第$_reconnectAttempt次,退避${delay}s)',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
await connect(host: _lastHost!, port: _lastPort!);
|
||||
final connectDone = DateTime.now();
|
||||
final connectMs = connectDone.difference(reconnectStart).inMilliseconds;
|
||||
debugPrint('✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2,'0')}:${connectDone.minute.toString().padLeft(2,'0')}:${connectDone.second.toString().padLeft(2,'0')}.${connectDone.millisecond.toString().padLeft(3,'0')} connect() 完成,耗时 ${connectMs}ms');
|
||||
debugPrint(
|
||||
'✅ [TCP-重连] ${connectDone.hour.toString().padLeft(2, '0')}:${connectDone.minute.toString().padLeft(2, '0')}:${connectDone.second.toString().padLeft(2, '0')}.${connectDone.millisecond.toString().padLeft(3, '0')} connect() 完成,耗时 ${connectMs}ms',
|
||||
);
|
||||
_reconnectAttempt = 0; // 🔥 重连成功,重置退避计数
|
||||
// 🔥 关键修复:等待5秒再调 HTTP switchDevice,给服务端时间完成相关操作
|
||||
final delayStart = DateTime.now();
|
||||
debugPrint('⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2,'0')}:${delayStart.minute.toString().padLeft(2,'0')}:${delayStart.second.toString().padLeft(2,'0')}.${delayStart.millisecond.toString().padLeft(3,'0')} 开始等待5秒...');
|
||||
debugPrint(
|
||||
'⏳ [TCP-重连] ${delayStart.hour.toString().padLeft(2, '0')}:${delayStart.minute.toString().padLeft(2, '0')}:${delayStart.second.toString().padLeft(2, '0')}.${delayStart.millisecond.toString().padLeft(3, '0')} 开始等待5秒...',
|
||||
);
|
||||
await Future.delayed(const Duration(milliseconds: 5000));
|
||||
final afterDelay = DateTime.now();
|
||||
final actualDelayMs = afterDelay.difference(delayStart).inMilliseconds;
|
||||
debugPrint('⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2,'0')}:${afterDelay.minute.toString().padLeft(2,'0')}:${afterDelay.second.toString().padLeft(2,'0')}.${afterDelay.millisecond.toString().padLeft(3,'0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice');
|
||||
debugPrint(
|
||||
'⏳ [TCP-重连] ${afterDelay.hour.toString().padLeft(2, '0')}:${afterDelay.minute.toString().padLeft(2, '0')}:${afterDelay.second.toString().padLeft(2, '0')}.${afterDelay.millisecond.toString().padLeft(3, '0')} 等待结束,实际耗时 ${actualDelayMs}ms,开始调 HTTP switchDevice',
|
||||
);
|
||||
try {
|
||||
final remoteControlCubit = GetIt.I<RemoteControlCubit>();
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
if (targetDevice != null) {
|
||||
debugPrint('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}');
|
||||
_logger.logWithLevel('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', shouldLog: true);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice('app', targetDevice.deviceName);
|
||||
debugPrint(
|
||||
'🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}',
|
||||
shouldLog: true,
|
||||
);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
'app',
|
||||
targetDevice.deviceName,
|
||||
);
|
||||
final switchDone = DateTime.now();
|
||||
final totalMs = switchDone.difference(reconnectStart).inMilliseconds;
|
||||
debugPrint('✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2,'0')}:${switchDone.minute.toString().padLeft(2,'0')}:${switchDone.second.toString().padLeft(2,'0')}.${switchDone.millisecond.toString().padLeft(3,'0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms');
|
||||
final totalMs = switchDone
|
||||
.difference(reconnectStart)
|
||||
.inMilliseconds;
|
||||
debugPrint(
|
||||
'✅ [TCP-重连] ${switchDone.hour.toString().padLeft(2, '0')}:${switchDone.minute.toString().padLeft(2, '0')}:${switchDone.second.toString().padLeft(2, '0')}.${switchDone.millisecond.toString().padLeft(3, '0')} HTTP switchDevice 成功,重连总耗时 ${totalMs}ms',
|
||||
);
|
||||
} else {
|
||||
debugPrint('⚠️ [TCP-重连] targetDevice 为 null,跳过 switchDevice');
|
||||
}
|
||||
@@ -479,7 +576,10 @@ class TcpClient {
|
||||
onReconnectSuccess?.call();
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] HTTP switchDevice 失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-重连] HTTP switchDevice 失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-重连] HTTP switchDevice 失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] connect 失败: $e');
|
||||
@@ -513,7 +613,10 @@ class TcpClient {
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
|
||||
if (targetDevice != null) {
|
||||
_logger.logWithLevel('🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'🔄 [TCP] 重连使用 targetDevice: ${targetDevice.deviceName}',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
@@ -521,7 +624,10 @@ class TcpClient {
|
||||
);
|
||||
} else {
|
||||
// 如果 targetDevice 为 null,使用传入的设备名作为兜底
|
||||
_logger.logWithLevel('⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⚠️ [TCP] targetDevice 为 null,使用传入的设备名: $devname',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
@@ -529,7 +635,10 @@ class TcpClient {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP] 获取 targetDevice 失败,使用传入的设备名: $devname, 错误: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
connectBySwitch(
|
||||
host: _lastHost!,
|
||||
port: _lastPort!,
|
||||
@@ -549,10 +658,111 @@ class TcpClient {
|
||||
_socket!.add(data);
|
||||
}
|
||||
|
||||
/// 🔥 断线丢帧日志节流时间戳:控制循环每 200ms 就会撞一次「未连接」,
|
||||
/// Permission requests need an awaited write result. Other send paths stay intact.
|
||||
/// Completion confirms local socket flushing, not server/Web receipt.
|
||||
Future<void> sendPermissionPacket(List<int> packet) async {
|
||||
final clock = Stopwatch()..start();
|
||||
final socket = _socket;
|
||||
final connection = _connectionId;
|
||||
var operation = 'wait_flush';
|
||||
var addAccepted = false;
|
||||
ControlPermissionDiagnostics.event('socket权限写入开始', {
|
||||
'connection': connection,
|
||||
'connected': socket != null,
|
||||
'pendingFlushes': _pendingSocketFlushes.length,
|
||||
'packetBytes': packet.length,
|
||||
});
|
||||
try {
|
||||
if (socket == null) throw const SocketException('TCP not connected');
|
||||
await _waitForSocketFlushes();
|
||||
if (!identical(socket, _socket))
|
||||
throw const SocketException('TCP changed');
|
||||
operation = 'add';
|
||||
socket.add(packet);
|
||||
addAccepted = true;
|
||||
ControlPermissionDiagnostics.event('socket权限add完成', {
|
||||
'connection': connection,
|
||||
'waitMs': clock.elapsedMilliseconds,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final beganUs = trace.elapsedUs;
|
||||
operation = 'flush';
|
||||
final pending = socket.flush();
|
||||
_observeDiagnosticFlush(pending, 0x12, beganUs);
|
||||
await pending;
|
||||
if (!identical(socket, _socket)) {
|
||||
throw const SocketException(
|
||||
'TCP connection changed during permission send',
|
||||
);
|
||||
}
|
||||
ControlPermissionDiagnostics.event('socket权限flush完成', {
|
||||
'connection': connection,
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
} catch (e) {
|
||||
ControlPermissionDiagnostics.event('socket权限写入失败', {
|
||||
'connection': connection,
|
||||
'operation': operation,
|
||||
'addAccepted': addAccepted,
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'durationMs': clock.elapsedMilliseconds,
|
||||
});
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔥 断线丢帧日志节流时间戳:控制循环每 250ms 就会撞一次「未连接」,
|
||||
/// 全量打印会淹掉日志文件,故 5 秒内只记一次(丢帧本身仍如实返回 false)。
|
||||
DateTime? _lastSendDropLogAt;
|
||||
|
||||
Future<void> _waitForSocketFlushes() async {
|
||||
while (_pendingSocketFlushes.isNotEmpty) {
|
||||
await Future.wait(
|
||||
_pendingSocketFlushes.toList().map((pending) async {
|
||||
try {
|
||||
await pending;
|
||||
} catch (_) {}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sole supported 0x00 path: newest movement, priority stop, >=250ms.
|
||||
Future<bool> sendControlPayload(
|
||||
List<int> payload, {
|
||||
bool priority = false,
|
||||
bool Function()? isCurrent,
|
||||
}) {
|
||||
final socket = _socket;
|
||||
final connection = _connectionId;
|
||||
final bytes = List<int>.of(payload);
|
||||
bool current() =>
|
||||
socket != null &&
|
||||
identical(socket, _socket) &&
|
||||
connection == _connectionId &&
|
||||
(isCurrent?.call() ?? true);
|
||||
return _controlFrames.submit(
|
||||
() async {
|
||||
await _waitForSocketFlushes();
|
||||
if (!current()) return false;
|
||||
final accepted = _sendRawNow(0x00, bytes);
|
||||
if (!accepted) return false;
|
||||
final pending = _lastRawFlush;
|
||||
if (pending == null) return false;
|
||||
try {
|
||||
await pending;
|
||||
return current();
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
priority: priority,
|
||||
isCurrent: current,
|
||||
);
|
||||
}
|
||||
|
||||
/// 把一帧协议数据写入 socket。
|
||||
///
|
||||
/// 返回 `false` = 这一帧**根本没交给系统 socket**(未连接,或写入抛异常)。
|
||||
@@ -561,7 +771,26 @@ class TcpClient {
|
||||
/// 而代码以为「已发送」——设备只保留了断开前最后一帧运动指令,正是
|
||||
/// 「松手了车还在走」的一条隐藏通路。现在必须由调用方判断结果自行兜底。
|
||||
bool sendRaw(int cmd, List<int> payload) {
|
||||
if (cmd == 0x00) {
|
||||
// Legacy callers may not bypass the common motion gate.
|
||||
unawaited(sendControlPayload(payload));
|
||||
return false; // Deferred requests must not claim a synchronous write.
|
||||
}
|
||||
return _sendRawNow(cmd, payload);
|
||||
}
|
||||
|
||||
bool _sendRawNow(int cmd, List<int> payload) {
|
||||
final trace = RemoteControlDiagnostics.instance;
|
||||
final beganUs = trace.elapsedUs;
|
||||
trace.event('socket_write_attempt', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'connected': _socket != null,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'payloadBytes': payload.length,
|
||||
});
|
||||
if (_socket == null) {
|
||||
trace.event('socket_not_connected', {'cmd': cmd, 'addAccepted': false});
|
||||
final now = DateTime.now();
|
||||
if (_lastSendDropLogAt == null ||
|
||||
now.difference(_lastSendDropLogAt!) >= const Duration(seconds: 5)) {
|
||||
@@ -586,10 +815,30 @@ class TcpClient {
|
||||
..addByte(0xAB);
|
||||
|
||||
final packet = builder.takeBytes();
|
||||
var operation = 'add';
|
||||
var addAccepted = false;
|
||||
try {
|
||||
_socket!.add(packet);
|
||||
addAccepted = true;
|
||||
final addedUs = trace.elapsedUs;
|
||||
trace.event('socket_add_accepted', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'addAccepted': true,
|
||||
'addGapUs': cmd == 0x00 && _diagnosticLastMotionAddUs != null
|
||||
? addedUs - _diagnosticLastMotionAddUs!
|
||||
: null,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'frameBytes': packet.length,
|
||||
'frameHex': _hex(packet),
|
||||
'serverReceiptConfirmed': false,
|
||||
});
|
||||
if (cmd == 0x00) _diagnosticLastMotionAddUs = addedUs;
|
||||
// 🔥 关键修复:强制flush,确保数据立即发送
|
||||
_socket!.flush();
|
||||
operation = 'flush';
|
||||
final pending = _socket!.flush();
|
||||
_lastRawFlush = pending;
|
||||
_observeDiagnosticFlush(pending, cmd, beganUs);
|
||||
// 联调日志:移到 add+flush 之后打印,证明这帧已真正交给系统 socket 发送缓冲
|
||||
// ("发出去之后"才有参考价值;仍非后端 ACK,仅代表 App 侧写入成功)(联调结束可移除)
|
||||
_logger.logWithLevel(
|
||||
@@ -599,6 +848,15 @@ class TcpClient {
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
trace.event('socket_write_error', {
|
||||
'cmd': cmd,
|
||||
'connection': _connectionId,
|
||||
'operation': operation,
|
||||
'addAccepted': addAccepted,
|
||||
'pendingFlushes': _diagnosticPendingFlushes,
|
||||
'errorType': e.runtimeType.toString(),
|
||||
'error': e.toString(),
|
||||
});
|
||||
_logger.logWithLevel(
|
||||
'🔗 [联调-TCP] sendRaw ❌写入socket失败 cmd=0x${cmd.toRadixString(16).padLeft(2, '0')} err=$e',
|
||||
level: 'ERROR',
|
||||
@@ -621,7 +879,7 @@ class TcpClient {
|
||||
..addByte(0xAA)
|
||||
..addByte(0xAB);
|
||||
_socket!.add(builder.takeBytes());
|
||||
debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB');
|
||||
// debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB');
|
||||
}
|
||||
|
||||
/// 启动心跳:主动定时发送 + 超时检测
|
||||
@@ -630,7 +888,10 @@ class TcpClient {
|
||||
void startHeartbeat({Duration interval = const Duration(seconds: 4)}) {
|
||||
if (_heartbeatTimer != null) return; // 防止重复启动
|
||||
debugPrint('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)');
|
||||
_logger.logWithLevel('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
// 🔥 主动定时发送心跳给服务端(每5秒)
|
||||
_heartbeatSendTimer?.cancel();
|
||||
@@ -650,7 +911,9 @@ class TcpClient {
|
||||
final wasRunning = _heartbeatTimer != null;
|
||||
_heartbeatTimer?.cancel();
|
||||
_heartbeatTimer = Timer(_heartbeatTimeout, () {
|
||||
debugPrint('⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开');
|
||||
debugPrint(
|
||||
'⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开',
|
||||
);
|
||||
_logger.logWithLevel('⚠️ [TCP] 心跳超时,判定连接断开', shouldLog: true);
|
||||
// 触发断开重连
|
||||
if (_socket != null) {
|
||||
@@ -759,7 +1022,9 @@ class TcpClient {
|
||||
var packets = _decoder.decode(data);
|
||||
for (var packet in packets) {
|
||||
// 🔥 最根部日志:收到任何推送都打印
|
||||
debugPrint('📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}');
|
||||
debugPrint(
|
||||
'📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}',
|
||||
shouldLog: true,
|
||||
@@ -791,7 +1056,10 @@ class TcpClient {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
@@ -802,7 +1070,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
@@ -940,7 +1210,9 @@ class TcpClient {
|
||||
// 🔥 关键日志:打印认证字符串,方便核对 Token
|
||||
debugPrint('🔑 [TCP] 正在发送认证包 (0x03)');
|
||||
debugPrint(' - Username: $username');
|
||||
debugPrint(' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...'); // 只打印前10位保护隐私
|
||||
debugPrint(
|
||||
' - Token: ${token?.substring(0, token!.length > 10 ? 10 : token!.length)}...',
|
||||
); // 只打印前10位保护隐私
|
||||
debugPrint(' - Full Auth String: $authString');
|
||||
_logger.logWithLevel('🔑 [TCP] 认证字符串: $authString', shouldLog: true);
|
||||
|
||||
@@ -1036,7 +1308,9 @@ class TcpClient {
|
||||
required String deviceName,
|
||||
}) async {
|
||||
debugPrint('🔌 [TCP-connectBySwitch] ========== 开始连接 ==========');
|
||||
debugPrint('🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName');
|
||||
debugPrint(
|
||||
'🔌 [TCP-connectBySwitch] Host: $host, Port: $port, Device: $deviceName',
|
||||
);
|
||||
|
||||
// 🔥 关键:取消之前的重连定时器,防止连接冲突
|
||||
_reconnectTimer?.cancel();
|
||||
@@ -1046,17 +1320,29 @@ class TcpClient {
|
||||
// 🔥 关键修复:如果已有连接正在进行中,等待连接就绪后只调 HTTP switchDevice
|
||||
if (_connecting) {
|
||||
debugPrint('✅ [TCP-connectBySwitch] 检测到 connect() 正在进行中,等待连接就绪...');
|
||||
_logger.logWithLevel('✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP-connectBySwitch] 连接进行中,等待后只做HTTP切换',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
await _connectionCompleter!.future.timeout(const Duration(seconds: 10));
|
||||
if (_connectionCompleter != null &&
|
||||
!_connectionCompleter!.isCompleted) {
|
||||
await _connectionCompleter!.future.timeout(
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
}
|
||||
// 连接就绪,只做 HTTP switchDevice,不创建新 TCP 连接
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
);
|
||||
debugPrint('✅ [TCP-connectBySwitch] 等待连接就绪后HTTP切换成功: $deviceName');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-connectBySwitch] 等待连接或HTTP切换失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1064,14 +1350,25 @@ class TcpClient {
|
||||
// 🔥 核心优化:如果 TCP 已连接,复用现有连接,只调 HTTP switchDevice
|
||||
// 不再销毁重建,避免推送空窗期导致延迟
|
||||
if (_socket != null) {
|
||||
debugPrint('✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName');
|
||||
_logger.logWithLevel('✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName', shouldLog: true);
|
||||
debugPrint(
|
||||
'✅ [TCP-connectBySwitch] 已有连接,复用现有连接,只调 HTTP switchDevice: $deviceName',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP-connectBySwitch] 复用连接,HTTP切换设备: $deviceName',
|
||||
shouldLog: true,
|
||||
);
|
||||
try {
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice("app", deviceName);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
);
|
||||
debugPrint('✅ [TCP-connectBySwitch] HTTP切换成功: $deviceName');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-connectBySwitch] HTTP切换失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-connectBySwitch] HTTP切换失败: $e', shouldLog: true);
|
||||
_logger.logWithLevel(
|
||||
'❌ [TCP-connectBySwitch] HTTP切换失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1156,8 +1453,13 @@ class TcpClient {
|
||||
onDone: () {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略',
|
||||
shouldLog: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
debugPrint('onDone [TCP] 被动连接已断开!_isSwitching=$_isSwitching');
|
||||
@@ -1170,7 +1472,9 @@ class TcpClient {
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
debugPrint(
|
||||
'⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略',
|
||||
);
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ 被动[TCP] 发生错误:$e');
|
||||
@@ -1255,7 +1559,9 @@ class TcpClient {
|
||||
);
|
||||
} else {
|
||||
// 兜底:如果 targetDevice 为 null,使用传入的 deviceName
|
||||
debugPrint('⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName');
|
||||
debugPrint(
|
||||
'⚠️ [TCP] targetDevice 为 null,使用传入的 deviceName: $deviceName',
|
||||
);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice(
|
||||
"app",
|
||||
deviceName,
|
||||
@@ -1270,8 +1576,13 @@ class TcpClient {
|
||||
|
||||
void _handleDisconnectBySwitch(String deviceName) {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效
|
||||
debugPrint('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', shouldLog: true);
|
||||
debugPrint(
|
||||
'🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId',
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId',
|
||||
shouldLog: true,
|
||||
);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,7 +111,12 @@ 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'
|
||||
? AppLocalizations.of(context).translate('remote_control.chassis')
|
||||
@@ -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() {
|
||||
|
||||
@@ -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');
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -63,6 +63,8 @@ class CCJoystick extends StatefulWidget {
|
||||
final AxisHint axisHint;
|
||||
final Function(JoystickValue) onValueChanged;
|
||||
final VoidCallback? onPress;
|
||||
/// Optional observer only; failures in diagnostics cannot affect gestures.
|
||||
final void Function(String event, Map<String, Object?> fields)? onDiagnostic;
|
||||
final Future<void> Function()? onPanEnd; // 🔥 修复:改为异步回调
|
||||
final double radius;
|
||||
|
||||
@@ -74,6 +76,7 @@ class CCJoystick extends StatefulWidget {
|
||||
required this.axisHint,
|
||||
required this.onValueChanged,
|
||||
this.onPress,
|
||||
this.onDiagnostic,
|
||||
this.onPanEnd, // 🔥 新增
|
||||
this.radius = 80,
|
||||
this.skin,
|
||||
@@ -89,6 +92,16 @@ class _CustomJoystickState extends State<CCJoystick>
|
||||
late AnimationController _floatController;
|
||||
bool _isPanning = false; // 🔥 跟踪是否正在拖拽
|
||||
|
||||
void _diagnose(String event, [Map<String, Object?> fields = const {}]) {
|
||||
try {
|
||||
widget.onDiagnostic?.call(event, {
|
||||
'axis': widget.axisHint.name,
|
||||
'panning': _isPanning,
|
||||
...fields,
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -116,7 +129,10 @@ class _CustomJoystickState extends State<CCJoystick>
|
||||
y = ((-_offset.dy / widget.radius) * 100).clamp(-100, 100).toInt();
|
||||
}
|
||||
|
||||
widget.onValueChanged(JoystickValue(_applyDeadZone(x), _applyDeadZone(y)));
|
||||
final outputX = _applyDeadZone(x);
|
||||
final outputY = _applyDeadZone(y);
|
||||
_diagnose('value', {'rawX': x, 'rawY': y, 'x': outputX, 'y': outputY});
|
||||
widget.onValueChanged(JoystickValue(outputX, outputY));
|
||||
}
|
||||
|
||||
int _applyDeadZone(int value, {int deadZone = 5}) {
|
||||
@@ -130,16 +146,17 @@ class _CustomJoystickState extends State<CCJoystick>
|
||||
onPointerUp: (_) async {
|
||||
if (_isPanning) {
|
||||
debugPrint('🛡️ [兜底] 全局指针抬起,强制归零');
|
||||
await _handlePanEnd();
|
||||
await _handlePanEnd(reason: 'pointer_up');
|
||||
}
|
||||
},
|
||||
onPointerCancel: (_) async {
|
||||
await _handlePanEnd();
|
||||
await _handlePanEnd(reason: 'pointer_cancel');
|
||||
},
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanStart: (_) {
|
||||
_isPanning = true;
|
||||
_diagnose('gesture_start');
|
||||
widget.onPress?.call();
|
||||
},
|
||||
onPanUpdate: (details) {
|
||||
@@ -165,12 +182,12 @@ class _CustomJoystickState extends State<CCJoystick>
|
||||
},
|
||||
onPanEnd: (_) async {
|
||||
debugPrint('✋ [正常] onPanEnd 触发');
|
||||
await _handlePanEnd();
|
||||
await _handlePanEnd(reason: 'pan_end');
|
||||
},
|
||||
onPanCancel: () async {
|
||||
// 🔥 新增:处理手势取消(如来电中断)
|
||||
debugPrint('⚠️ [异常] onPanCancel 触发');
|
||||
await _handlePanEnd();
|
||||
await _handlePanEnd(reason: 'pan_cancel');
|
||||
},
|
||||
child: AnimatedBuilder(
|
||||
animation: _floatController,
|
||||
@@ -192,7 +209,8 @@ class _CustomJoystickState extends State<CCJoystick>
|
||||
}
|
||||
|
||||
// 🔥 统一的松手处理逻辑
|
||||
Future<void> _handlePanEnd() async {
|
||||
Future<void> _handlePanEnd({required String reason}) async {
|
||||
_diagnose('gesture_end', {'reason': reason, 'willStop': _isPanning});
|
||||
if (!_isPanning) return;
|
||||
_isPanning = false;
|
||||
setState(() => _offset = Offset.zero); // 归位
|
||||
|
||||
84
test/control_frame_scheduler_test.dart
Normal file
84
test/control_frame_scheduler_test.dart
Normal file
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/tcp/control_frame_scheduler.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('movement waits 250ms and replaces pending older input', (
|
||||
tester,
|
||||
) async {
|
||||
var nowUs = 0;
|
||||
final scheduler = ControlFrameScheduler(nowUs: () => nowUs);
|
||||
final writes = <int>[];
|
||||
Future<bool> write(int input) async {
|
||||
writes.add(input);
|
||||
return true;
|
||||
}
|
||||
|
||||
final first = scheduler.submit(
|
||||
() => write(10),
|
||||
priority: false,
|
||||
isCurrent: () => true,
|
||||
);
|
||||
await tester.pump();
|
||||
expect(await first, isTrue);
|
||||
nowUs = 100000;
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
final replaced = scheduler.submit(
|
||||
() => write(20),
|
||||
priority: false,
|
||||
isCurrent: () => true,
|
||||
);
|
||||
nowUs = 200000;
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
final latest = scheduler.submit(
|
||||
() => write(30),
|
||||
priority: false,
|
||||
isCurrent: () => true,
|
||||
);
|
||||
expect(await replaced, isFalse);
|
||||
expect(writes, [10]);
|
||||
nowUs = 249000;
|
||||
await tester.pump(const Duration(milliseconds: 49));
|
||||
expect(writes, [10]);
|
||||
nowUs = 250000;
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(await latest, isTrue);
|
||||
expect(writes, [10, 30]);
|
||||
});
|
||||
|
||||
testWidgets('priority zero replaces movement and shares the 250ms gate', (
|
||||
tester,
|
||||
) async {
|
||||
var nowUs = 0;
|
||||
final scheduler = ControlFrameScheduler(nowUs: () => nowUs);
|
||||
final writes = <int>[];
|
||||
Future<bool> write(int input) async {
|
||||
writes.add(input);
|
||||
return true;
|
||||
}
|
||||
|
||||
scheduler.submit(() => write(50), priority: false, isCurrent: () => true);
|
||||
await tester.pump();
|
||||
nowUs = 100000;
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
final movement = scheduler.submit(
|
||||
() => write(75),
|
||||
priority: false,
|
||||
isCurrent: () => true,
|
||||
);
|
||||
nowUs = 150000;
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
final stop = scheduler.submit(
|
||||
() => write(0),
|
||||
priority: true,
|
||||
isCurrent: () => true,
|
||||
);
|
||||
expect(await movement, isFalse);
|
||||
nowUs = 249000;
|
||||
await tester.pump(const Duration(milliseconds: 99));
|
||||
expect(writes, [50]);
|
||||
nowUs = 250000;
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(await stop, isTrue);
|
||||
expect(writes, [50, 0]);
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/de
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/domain/usecases/device_control_mode_usecases.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_control_mode/presentation/cubit/control_mode_entry_cubit.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 'support/control_mode_fakes.dart';
|
||||
|
||||
final _translations = <String, AppLocalizations>{};
|
||||
@@ -215,6 +216,94 @@ void main() {
|
||||
expect(drives, 1);
|
||||
});
|
||||
|
||||
testWidgets('independent emergency and settings stay usable before mode confirmation', (
|
||||
tester,
|
||||
) async {
|
||||
repo.initial = '2';
|
||||
sl.registerSingleton(WatchDeviceControlModeUseCase(repo));
|
||||
sl.registerSingleton(ChangeDeviceControlModeUseCase(repo));
|
||||
var stops = 0;
|
||||
var originalStops = 0;
|
||||
var drives = 0;
|
||||
var activations = 0;
|
||||
await tester.pumpWidget(
|
||||
app(
|
||||
ControlModeEntryGate(
|
||||
deviceId: 'SN002',
|
||||
target: ControlModeTarget.remote,
|
||||
cancelToPreview: true,
|
||||
emergencyStopControl: TextButton(
|
||||
onPressed: () => stops++,
|
||||
child: const Text('independent stop'),
|
||||
),
|
||||
onReady: () => activations++,
|
||||
child: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
ModeIndependentControl(
|
||||
child: TextButton(
|
||||
key: const Key('original-stop'),
|
||||
onPressed: () => originalStops++,
|
||||
child: const Text('original stop'),
|
||||
),
|
||||
),
|
||||
Builder(
|
||||
builder: (context) => ModeIndependentControl(
|
||||
child: IconButton(
|
||||
key: const Key('independent-settings'),
|
||||
icon: const Icon(Icons.settings),
|
||||
onPressed: () => showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('video settings'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('close settings'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
key: const Key('blocked-drive'),
|
||||
onPressed: () => drives++,
|
||||
child: const Text('drive'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
// 模式弹窗内急停可用,不会触发模式切换或激活遥控。
|
||||
await tester.tap(find.text('independent stop').last);
|
||||
expect(stops, 1);
|
||||
expect(repo.requests, isEmpty);
|
||||
expect(activations, 0);
|
||||
await tester.tap(find.byIcon(Icons.close_rounded).first);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('independent stop'), findsNothing);
|
||||
await tester.tap(find.byKey(const Key('original-stop')));
|
||||
expect(originalStops, 1);
|
||||
expect(stops, 1);
|
||||
await tester.tap(find.byKey(const Key('independent-settings')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('video settings'), findsOneWidget);
|
||||
await tester.tap(find.text('close settings'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(
|
||||
find.byKey(const Key('blocked-drive')),
|
||||
warnIfMissed: false,
|
||||
);
|
||||
expect(drives, 0);
|
||||
expect(activations, 0);
|
||||
expect(repo.requests, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('取消遥控模式确认返回来源页,不激活控制或下发切换', (tester) async {
|
||||
repo.initial = '2';
|
||||
sl.registerSingleton(WatchDeviceControlModeUseCase(repo));
|
||||
|
||||
154
test/device_emergency_stop_status_test.dart
Normal file
154
test/device_emergency_stop_status_test.dart
Normal file
@@ -0,0 +1,154 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/host_realtime_message_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_message.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/task_message_repository.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status_entity.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';
|
||||
|
||||
class _MqttClient extends Fake implements MqttClient {
|
||||
final messages = StreamController<MqttMessage>.broadcast();
|
||||
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
@override
|
||||
Future<void> subscribe(String topic) async {}
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {}
|
||||
|
||||
void send(Map<String, dynamic> data, {String sn = 'robot-1'}) {
|
||||
messages.add(
|
||||
MqttMessage(
|
||||
topic: 'device/$sn/host/realTime/message',
|
||||
payload: jsonEncode({'data': data}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Tasks extends Fake implements TaskMessageRepository {
|
||||
@override
|
||||
Stream<TaskArriveEntity> get taskArriveStream => const Stream.empty();
|
||||
@override
|
||||
Stream<TaskStatusEntity> get taskStatusStream => const Stream.empty();
|
||||
}
|
||||
|
||||
class _Logger extends Fake implements ILoggerService {
|
||||
@override
|
||||
void log(
|
||||
String message, {
|
||||
bool isWarning = false,
|
||||
Map<String, dynamic>? data,
|
||||
}) {}
|
||||
}
|
||||
|
||||
class _TcpClient extends Fake implements TcpClient {}
|
||||
|
||||
class _Dispatcher extends Fake implements NetMessageDispatcher {}
|
||||
|
||||
void main() {
|
||||
test('missing and invalid emergency states stay unknown', () {
|
||||
expect(HostRealtimeMessageEntity.fromJson({}).emergencyStop, isNull);
|
||||
for (final raw in [null, '', 'unknown', 2, -1, [], {}]) {
|
||||
expect(
|
||||
HostRealtimeMessageEntity.fromJson({
|
||||
'emergency_stop': raw,
|
||||
}).emergencyStop,
|
||||
isNull,
|
||||
);
|
||||
}
|
||||
for (final raw in [true, 1, '1', 'true']) {
|
||||
expect(
|
||||
HostRealtimeMessageEntity.fromJson({
|
||||
'emergency_stop': raw,
|
||||
}).emergencyStop,
|
||||
isTrue,
|
||||
);
|
||||
}
|
||||
for (final raw in [false, 0, '0', 'false']) {
|
||||
expect(
|
||||
HostRealtimeMessageEntity.fromJson({
|
||||
'emergency_stop': raw,
|
||||
}).emergencyStop,
|
||||
isFalse,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'location copies preserve emergency state and missing reports clear it',
|
||||
() {
|
||||
const stopped = RunningStatusEntity(emergencyStop: true);
|
||||
expect(stopped.copyWith(latitude: 31.2).emergencyStop, isTrue);
|
||||
final released = stopped.copyWith(emergencyStop: false);
|
||||
expect(released.emergencyStop, isFalse);
|
||||
expect(released, isNot(stopped));
|
||||
expect(released.copyWith(emergencyStop: null).emergencyStop, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'host reports update detail state without GPS and reset on device change',
|
||||
(tester) async {
|
||||
final mqtt = _MqttClient();
|
||||
final source = MowerRealtimeDataSourceImpl(mqtt);
|
||||
sl.registerSingleton<ILoggerService>(_Logger());
|
||||
sl.registerSingleton<TaskMessageRepository>(_Tasks());
|
||||
sl.registerSingleton<MowerRealtimeRepository>(
|
||||
MowerRealtimeRepositoryImpl(source),
|
||||
);
|
||||
final bloc = DeviceStatusBloc(_Dispatcher(), client: _TcpClient());
|
||||
addTearDown(() async {
|
||||
await bloc.close();
|
||||
await source.stopListening();
|
||||
source.dispose();
|
||||
await mqtt.messages.close();
|
||||
await sl.reset();
|
||||
});
|
||||
|
||||
bloc.startMqttRealtimeListening('robot-1');
|
||||
await tester.pump();
|
||||
for (final data in <Map<String, dynamic>>[
|
||||
{'emergency_stop': false},
|
||||
{'emergency_stop': true},
|
||||
{'emergency_stop': 0},
|
||||
{},
|
||||
]) {
|
||||
mqtt.send(data);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 501));
|
||||
expect(
|
||||
(bloc.state as DeviceStatusUpdated).status.emergencyStop,
|
||||
data.containsKey('emergency_stop')
|
||||
? data['emergency_stop'] != 0 && data['emergency_stop'] != false
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
mqtt.send({'emergency_stop': true});
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 501));
|
||||
bloc.startMqttRealtimeListening('robot-2');
|
||||
await tester.pump();
|
||||
expect(bloc.state, isA<DeviceStatusInitial>());
|
||||
mqtt.send({'emergency_stop': true});
|
||||
mqtt.send({'control_mode': 1}, sn: 'robot-2');
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 501));
|
||||
expect((bloc.state as DeviceStatusUpdated).status.emergencyStop, isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
141
test/device_emergency_stop_test.dart
Normal file
141
test/device_emergency_stop_test.dart
Normal file
@@ -0,0 +1,141 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/env/env_config.dart';
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/datasources/emergency_stop_remote_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/data/repositories/device_emergency_stop_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_target.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart';
|
||||
|
||||
void main() {
|
||||
late Dio dio;
|
||||
late RequestDeviceEmergencyStopUseCase request;
|
||||
late List<RequestOptions> requests;
|
||||
dynamic body;
|
||||
int status = 200;
|
||||
DioExceptionType? errorType;
|
||||
|
||||
setUp(() {
|
||||
requests = [];
|
||||
body = {'code': 200};
|
||||
status = 200;
|
||||
errorType = null;
|
||||
dio = Dio();
|
||||
// Resolve locally: these tests never contact a backend or a machine.
|
||||
dio.interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
requests.add(options);
|
||||
if (errorType != null) {
|
||||
handler.reject(
|
||||
DioException(requestOptions: options, type: errorType!),
|
||||
);
|
||||
} else {
|
||||
handler.resolve(
|
||||
Response<dynamic>(
|
||||
requestOptions: options,
|
||||
statusCode: status,
|
||||
data: body,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
request = RequestDeviceEmergencyStopUseCase(
|
||||
DeviceEmergencyStopRepositoryImpl(EmergencyStopRemoteDatasource(dio)),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() => dio.close(force: true));
|
||||
|
||||
for (final target in EmergencyStopTarget.values) {
|
||||
test(
|
||||
'${target.name} uses GET query parameters in selected environment',
|
||||
() async {
|
||||
expect(requests, isEmpty);
|
||||
final result = await request(' DEVICE-1 ', target);
|
||||
expect(result.isRight(), isTrue);
|
||||
final options = requests.single;
|
||||
expect(options.method, 'GET');
|
||||
expect(options.data, isNull);
|
||||
expect(options.queryParameters, {
|
||||
'deviceId': 'DEVICE-1',
|
||||
'eStop': target == EmergencyStopTarget.engage ? 1 : 0,
|
||||
});
|
||||
expect(options.uri.path, '/iot/host/eStopChange');
|
||||
expect(options.uri.origin, EnvConfig.baseUrl);
|
||||
const environment = String.fromEnvironment('ENV', defaultValue: 'test');
|
||||
expect(options.uri.port, environment == 'prod' ? 8081 : 59003);
|
||||
expect(options.headers['Cache-Control'], 'no-store');
|
||||
// API request completion has no device-state result attached to it.
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('empty device ID fails without sending a request', () async {
|
||||
final result = await request(' ', EmergencyStopTarget.engage);
|
||||
expect(result.isLeft(), isTrue);
|
||||
expect(requests, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'string business success code follows existing host convention',
|
||||
() async {
|
||||
body = {'code': '200', 'data': true};
|
||||
expect(
|
||||
(await request('DEVICE-1', EmergencyStopTarget.engage)).isRight(),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
final invalidResponses = <String, dynamic>{
|
||||
'empty response': null,
|
||||
'text response': 'ok',
|
||||
'missing business code': {'data': true},
|
||||
'business rejection': {'code': 500},
|
||||
'explicit failure': {'code': 200, 'data': false},
|
||||
'top-level rejection': {'code': 200, 'accepted': false},
|
||||
'device rejection': {
|
||||
'code': 200,
|
||||
'data': {'accepted': false},
|
||||
},
|
||||
};
|
||||
for (final response in invalidResponses.entries) {
|
||||
test('${response.key} is not reported as accepted', () async {
|
||||
body = response.value;
|
||||
final result = await request('DEVICE-1', EmergencyStopTarget.release);
|
||||
expect(result.isLeft(), isTrue);
|
||||
result.fold(
|
||||
(failure) => expect(failure, isA<ServerFailure>()),
|
||||
(_) => fail('Unexpected success'),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('HTTP failure is not masked by a successful business code', () async {
|
||||
status = 500;
|
||||
expect(
|
||||
(await request('DEVICE-1', EmergencyStopTarget.engage)).isLeft(),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
for (final type in [
|
||||
DioExceptionType.connectionTimeout,
|
||||
DioExceptionType.sendTimeout,
|
||||
DioExceptionType.receiveTimeout,
|
||||
DioExceptionType.connectionError,
|
||||
]) {
|
||||
test('${type.name} remains unconfirmed and is not retried', () async {
|
||||
errorType = type;
|
||||
final result = await request('DEVICE-1', EmergencyStopTarget.release);
|
||||
result.fold(
|
||||
(failure) => expect(failure, isA<NetworkFailure>()),
|
||||
(_) => fail('Unexpected success'),
|
||||
);
|
||||
expect(requests, hasLength(1));
|
||||
});
|
||||
}
|
||||
}
|
||||
193
test/pv_realtime_telemetry_test.dart
Normal file
193
test/pv_realtime_telemetry_test.dart
Normal file
@@ -0,0 +1,193 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/datasources/mower_realtime_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/data/repositories/mower_realtime_repository_impl.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/host_realtime_message_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_arrive_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/entities/task_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_message.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/task_message_repository.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/running_status_entity.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/pv_control/presentation/models/pv_telemetry.dart';
|
||||
|
||||
class _Mqtt extends Fake implements MqttClient {
|
||||
final messages = StreamController<MqttMessage>.broadcast();
|
||||
@override
|
||||
Stream<MqttMessage> get messageStream => messages.stream;
|
||||
@override
|
||||
Future<void> subscribe(String topic) async {}
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {}
|
||||
|
||||
void send(String topic, Object data) => messages.add(
|
||||
MqttMessage(topic: topic, payload: jsonEncode({'data': data})),
|
||||
);
|
||||
}
|
||||
|
||||
class _Tasks extends Fake implements TaskMessageRepository {
|
||||
@override
|
||||
Stream<TaskArriveEntity> get taskArriveStream => const Stream.empty();
|
||||
@override
|
||||
Stream<TaskStatusEntity> get taskStatusStream => const Stream.empty();
|
||||
}
|
||||
|
||||
class _Logger extends Fake implements ILoggerService {
|
||||
@override
|
||||
void log(
|
||||
String message, {
|
||||
bool isWarning = false,
|
||||
Map<String, dynamic>? data,
|
||||
}) {}
|
||||
}
|
||||
|
||||
class _Tcp extends Fake implements TcpClient {}
|
||||
|
||||
class _Dispatcher extends Fake implements NetMessageDispatcher {}
|
||||
|
||||
void main() {
|
||||
test('missing reports stay unknown and reported zero is a real value', () {
|
||||
final empty = PvTelemetry.fromRunningStatus(const RunningStatusEntity());
|
||||
expect(empty.speed, isNull);
|
||||
expect(empty.leftMeasuredRpm, isNull);
|
||||
expect(empty.mowerRpm, isNull);
|
||||
expect(empty.battery, isNull);
|
||||
final zero = PvTelemetry.fromRunningStatus(
|
||||
RunningStatusEntity(
|
||||
knifeCuttingSpeed: '0',
|
||||
hostRealtime: HostRealtimeMessageEntity.fromJson({
|
||||
'linear_speed': 0,
|
||||
'left_measured_rpm': '0',
|
||||
'battery_percentage': 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(zero.speed, 0);
|
||||
expect(zero.leftMeasuredRpm, 0);
|
||||
expect(zero.rightMeasuredRpm, isNull);
|
||||
expect(zero.mowerRpm, 0);
|
||||
expect(zero.battery, 0);
|
||||
});
|
||||
|
||||
test('invalid numbers stay unknown, signed wheel speeds preserve units', () {
|
||||
final telemetry = PvTelemetry.fromRunningStatus(
|
||||
RunningStatusEntity(
|
||||
knifeCuttingSpeed: 'NaN',
|
||||
hostRealtime: HostRealtimeMessageEntity.fromJson({
|
||||
'linear_speed': -0.25,
|
||||
'left_measured_rpm': -22.5,
|
||||
'right_measured_rpm': 'bad',
|
||||
'left_target_rpm': -25,
|
||||
'right_target_rpm': 'Infinity',
|
||||
'battery_percentage': 101,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(telemetry.speed, -0.25);
|
||||
expect(telemetry.leftMeasuredRpm, -22.5);
|
||||
expect(telemetry.leftTargetRpm, -25);
|
||||
expect(telemetry.rightMeasuredRpm, isNull);
|
||||
expect(telemetry.rightTargetRpm, isNull);
|
||||
expect(telemetry.mowerRpm, isNull);
|
||||
expect(telemetry.battery, isNull);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'MQTT reaches HUD without GPS, clears missing values and resets devices',
|
||||
(tester) async {
|
||||
final mqtt = _Mqtt();
|
||||
final source = MowerRealtimeDataSourceImpl(mqtt);
|
||||
sl.registerSingleton<ILoggerService>(_Logger());
|
||||
sl.registerSingleton<TaskMessageRepository>(_Tasks());
|
||||
sl.registerSingleton<MowerRealtimeRepository>(
|
||||
MowerRealtimeRepositoryImpl(source),
|
||||
);
|
||||
final bloc = DeviceStatusBloc(_Dispatcher(), client: _Tcp());
|
||||
addTearDown(() async {
|
||||
await bloc.close();
|
||||
await source.stopListening();
|
||||
source.dispose();
|
||||
await mqtt.messages.close();
|
||||
await sl.reset();
|
||||
});
|
||||
PvTelemetry snapshot() => PvTelemetry.fromRunningStatus(
|
||||
bloc.state is DeviceStatusUpdated
|
||||
? (bloc.state as DeviceStatusUpdated).status
|
||||
: null,
|
||||
);
|
||||
Future<void> flush() async {
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 501));
|
||||
}
|
||||
|
||||
const hostTopic = 'device/robot-1/host/realTime/message';
|
||||
const vehicleTopic = 'mower/robot-1/property/realtime/post';
|
||||
bloc.startMqttRealtimeListening('robot-1');
|
||||
await tester.pump();
|
||||
mqtt.send(hostTopic, {
|
||||
'linear_speed': -0.3,
|
||||
'left_measured_rpm': -10,
|
||||
'right_measured_rpm': -11,
|
||||
'left_target_rpm': -12,
|
||||
'right_target_rpm': -13,
|
||||
'motion': 'moving',
|
||||
'battery_percentage': 75,
|
||||
});
|
||||
mqtt.send(vehicleTopic, [
|
||||
{'name': 'cuttingSpeed', 'value': 2400, 'unit': 'rpm'},
|
||||
]);
|
||||
await flush();
|
||||
expect(snapshot().speed, -0.3);
|
||||
expect(snapshot().leftMeasuredRpm, -10);
|
||||
expect(snapshot().rightMeasuredRpm, -11);
|
||||
expect(snapshot().leftTargetRpm, -12);
|
||||
expect(snapshot().rightTargetRpm, -13);
|
||||
expect(snapshot().mowerRpm, 2400);
|
||||
expect(snapshot().motion, 'moving');
|
||||
|
||||
mqtt.send(vehicleTopic, [
|
||||
{'name': 'cuttingSpeed', 'value': '0', 'unit': 'rpm'},
|
||||
]);
|
||||
await flush();
|
||||
expect(snapshot().mowerRpm, 0);
|
||||
expect(snapshot().speed, -0.3);
|
||||
mqtt.send(hostTopic, {'linear_speed': 0, 'left_measured_rpm': 0});
|
||||
await flush();
|
||||
expect(snapshot().speed, 0);
|
||||
expect(snapshot().rightMeasuredRpm, isNull);
|
||||
expect(snapshot().leftTargetRpm, isNull);
|
||||
expect(snapshot().battery, isNull);
|
||||
|
||||
// Both frames parse to the same legacy numeric defaults. Presence must still emit.
|
||||
mqtt.send(hostTopic, {});
|
||||
await flush();
|
||||
expect(snapshot().speed, isNull);
|
||||
expect(snapshot().leftMeasuredRpm, isNull);
|
||||
expect(snapshot().mowerRpm, 0);
|
||||
mqtt.send(vehicleTopic, [
|
||||
{'name': 'voltage', 'value': '48', 'unit': 'V'},
|
||||
]);
|
||||
await flush();
|
||||
expect(snapshot().speed, isNull);
|
||||
expect(snapshot().leftMeasuredRpm, isNull);
|
||||
expect(snapshot().mowerRpm, isNull);
|
||||
|
||||
bloc.startMqttRealtimeListening('robot-2');
|
||||
await tester.pump();
|
||||
mqtt.send(hostTopic, {'linear_speed': 1});
|
||||
mqtt.send('device/robot-2/host/realTime/message', {'control_mode': 3});
|
||||
await flush();
|
||||
expect(snapshot().speed, isNull);
|
||||
expect(snapshot().mowerRpm, isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
135
test/remote_control_diagnostics_test.dart
Normal file
135
test/remote_control_diagnostics_test.dart
Normal file
@@ -0,0 +1,135 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart';
|
||||
import 'package:maibu_satabot_v2/core/protocol/machine_protocol_codec.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart';
|
||||
|
||||
List<Map<String, dynamic>> records(List<String> batches) => batches
|
||||
.join()
|
||||
.split('\n')
|
||||
.where((line) => line.isNotEmpty)
|
||||
.map((line) => jsonDecode(line) as Map<String, dynamic>)
|
||||
.toList();
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'frame correlation survives asynchronous completion and a new session',
|
||||
() async {
|
||||
final batches = <String>[];
|
||||
final trace = RemoteControlDiagnostics(
|
||||
append: (s) async => batches.add(s),
|
||||
);
|
||||
trace.begin('SN-1', {'intervalMs': 250});
|
||||
final completion = Completer<void>();
|
||||
late Future<void> observed;
|
||||
final result = trace.frame('loop', {'tick': 2}, () {
|
||||
trace.event('conversion', {'linearMps': 1.0});
|
||||
observed = completion.future.then(
|
||||
(_) => trace.event('socket_flush_complete', {}),
|
||||
);
|
||||
return true;
|
||||
});
|
||||
trace.begin('SN-2', {'intervalMs': 250});
|
||||
completion.complete();
|
||||
await observed;
|
||||
await trace.flush();
|
||||
final lines = records(batches);
|
||||
final conversion = lines.singleWhere((r) => r['stage'] == 'conversion');
|
||||
final flushed = lines.singleWhere(
|
||||
(r) => r['stage'] == 'socket_flush_complete',
|
||||
);
|
||||
expect(result, isTrue);
|
||||
expect(flushed['frame'], conversion['frame']);
|
||||
expect(flushed['session'], conversion['session']);
|
||||
expect(flushed['device'], 'SN-1');
|
||||
expect(flushed['source'], 'loop');
|
||||
},
|
||||
);
|
||||
|
||||
test('file writes are serialized and preserve event order', () async {
|
||||
final batches = <String>[];
|
||||
final held = Completer<void>();
|
||||
var active = 0;
|
||||
var maxActive = 0;
|
||||
final trace = RemoteControlDiagnostics(
|
||||
append: (s) async {
|
||||
active++;
|
||||
if (active > maxActive) maxActive = active;
|
||||
await held.future;
|
||||
batches.add(s);
|
||||
active--;
|
||||
},
|
||||
);
|
||||
trace.event('first', {});
|
||||
final writing = trace.flush();
|
||||
trace.event('second', {});
|
||||
final again = trace.flush();
|
||||
held.complete();
|
||||
await Future.wait([writing, again]);
|
||||
await trace.flush();
|
||||
expect(maxActive, 1);
|
||||
expect(records(batches).map((r) => r['stage']), ['first', 'second']);
|
||||
});
|
||||
|
||||
test(
|
||||
'disk failures do not interrupt control and missing records are marked',
|
||||
() async {
|
||||
final batches = <String>[];
|
||||
var fail = true;
|
||||
final trace = RemoteControlDiagnostics(
|
||||
append: (s) async {
|
||||
if (fail) throw StateError('test disk failure');
|
||||
batches.add(s);
|
||||
},
|
||||
);
|
||||
final result = trace.frame('stop', {}, () {
|
||||
trace.event('socket_write_attempt', {});
|
||||
return false;
|
||||
});
|
||||
await trace.flush();
|
||||
fail = false;
|
||||
trace.event('next', {});
|
||||
await trace.flush();
|
||||
expect(result, isFalse);
|
||||
expect(records(batches).first, {
|
||||
'stage': 'diagnostic_overflow',
|
||||
'dropped': 1,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('buffer is bounded and discarded records are explicit', () async {
|
||||
final batches = <String>[];
|
||||
final trace = RemoteControlDiagnostics(append: (s) async => batches.add(s));
|
||||
for (var i = 0; i < 2010; i++) {
|
||||
trace.event('tick', {'tick': i});
|
||||
}
|
||||
await trace.flush();
|
||||
final lines = records(batches);
|
||||
expect(lines.length, 2001);
|
||||
expect(lines.first['dropped'], 10);
|
||||
expect(lines[1]['tick'], 10);
|
||||
expect(lines.last['tick'], 2009);
|
||||
});
|
||||
|
||||
test(
|
||||
'current velocity conversion and float64 little-endian payload stay intact',
|
||||
() {
|
||||
final algorithm = DiffSteerUseCase();
|
||||
for (final y in [-100, -50, 0, 50, 100]) {
|
||||
final speeds = algorithm.calculate(0, y);
|
||||
final payload = MachineProtocolCodec.encodeRemoteControlPayload(
|
||||
linear: speeds['linear']!,
|
||||
angular: speeds['angular']!,
|
||||
);
|
||||
final decoded = ByteData.sublistView(payload);
|
||||
expect(payload.length, 20);
|
||||
expect(decoded.getFloat64(0, Endian.little), y / 100);
|
||||
expect(decoded.getFloat64(8, Endian.little), 0);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
824
test/remote_control_permission_test.dart
Normal file
824
test/remote_control_permission_test.dart
Normal file
@@ -0,0 +1,824 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/entities/machine_control_status_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_stop_button.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/emergency_overlay.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/i_logger_service.dart';
|
||||
import 'package:maibu_satabot_v2/core/logging/remote_control_diagnostics.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/tcp/tcp_client.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_target.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/entities/emergency_stop_failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/repositories/device_emergency_stop_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/device_emergency_stop/domain/usecases/request_device_emergency_stop_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/entities/control_permission_failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/request_control_permission_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart';
|
||||
|
||||
class _Logger implements ILoggerService {
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _LoadedLocalizations extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _LoadedLocalizations(this.value);
|
||||
final AppLocalizations value;
|
||||
@override
|
||||
bool isSupported(Locale locale) => true;
|
||||
@override
|
||||
Future<AppLocalizations> load(Locale locale) => SynchronousFuture(value);
|
||||
@override
|
||||
bool shouldReload(_LoadedLocalizations old) => false;
|
||||
}
|
||||
|
||||
class _Devices implements DeviceRepository {
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _Status implements DeviceStatusBloc {
|
||||
static ({String sn, bool? active, DateTime receivedAt})? reading;
|
||||
@override
|
||||
({String sn, bool? active, DateTime receivedAt})? get emergencyStopReading =>
|
||||
reading;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _Tcp implements TcpClient {
|
||||
final packets = StreamController<RawPacket>.broadcast(sync: true);
|
||||
bool connected = true;
|
||||
@override
|
||||
bool get isConnected => connected;
|
||||
@override
|
||||
Stream<RawPacket> get packetStream => packets.stream;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _Dispatcher implements NetMessageDispatcher {
|
||||
_Dispatcher(this.tcp);
|
||||
final _Tcp tcp;
|
||||
@override
|
||||
Stream<RawPacket> onCommand(int command) =>
|
||||
tcp.packetStream.where((p) => p.command == command);
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _Repository implements RemoteControlRepository {
|
||||
int motionSends = 0;
|
||||
final sentFrames = <MachineControlStatusEntity>[];
|
||||
@override
|
||||
Future<bool> sendControlMachineCmd(
|
||||
MachineControlStatusEntity status, {
|
||||
bool priority = false,
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
if (isCurrent != null && !isCurrent()) return false;
|
||||
motionSends++;
|
||||
sentFrames.add(status);
|
||||
return true;
|
||||
}
|
||||
|
||||
int queries = 0;
|
||||
int sends = 0;
|
||||
Map<String, dynamic> info = {'hasPermission': false, 'owner': 'web'};
|
||||
Completer<Map<String, dynamic>>? query;
|
||||
Completer<void>? write;
|
||||
ControlPermissionFailure? queryError;
|
||||
ControlPermissionFailure? sendError;
|
||||
@override
|
||||
Future<Map<String, dynamic>> requestControlPermission(
|
||||
String deviceName,
|
||||
String deviceId,
|
||||
) async {
|
||||
queries++;
|
||||
if (queryError != null) throw queryError!;
|
||||
return query?.future ?? info;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sendTcpPermissionRequest(
|
||||
String deviceName, {
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
if (isCurrent != null && !isCurrent()) return;
|
||||
sends++;
|
||||
if (sendError != null) throw sendError!;
|
||||
await write?.future;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => null;
|
||||
}
|
||||
|
||||
class _Cubit extends RemoteControlCubit {
|
||||
_Cubit(_Repository repo, _Tcp tcp, _Emergency emergency)
|
||||
: super(
|
||||
repo,
|
||||
RequestControlPermissionUseCase(repo),
|
||||
_Devices(),
|
||||
tcp,
|
||||
_Dispatcher(tcp),
|
||||
_Status(),
|
||||
requestEmergencyStop: RequestDeviceEmergencyStopUseCase(emergency),
|
||||
emergencyNow: () => TestWidgetsFlutterBinding.instance.clock.now(),
|
||||
);
|
||||
int stops = 0;
|
||||
@override
|
||||
Future<void> stopAllMovement({String reason = 'unspecified'}) async {
|
||||
stops++;
|
||||
}
|
||||
}
|
||||
|
||||
class _Emergency implements DeviceEmergencyStopRepository {
|
||||
bool autoReport = true;
|
||||
void Function()? onReport;
|
||||
final calls = <(String, EmergencyStopTarget)>[];
|
||||
Either<Failure, Unit> result = const Right(unit);
|
||||
Completer<Either<Failure, Unit>>? pending;
|
||||
@override
|
||||
Future<Either<Failure, Unit>> request(
|
||||
String deviceId,
|
||||
EmergencyStopTarget target,
|
||||
) async {
|
||||
calls.add((deviceId, target));
|
||||
final response = await (pending?.future ?? Future.value(result));
|
||||
if (autoReport && response.isRight()) {
|
||||
_Status.reading = (
|
||||
sn: deviceId,
|
||||
active: target == EmergencyStopTarget.engage,
|
||||
receivedAt: TestWidgetsFlutterBinding.instance.clock.now(),
|
||||
);
|
||||
onReport?.call();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late _Emergency emergency;
|
||||
void scenario(
|
||||
String name,
|
||||
Future<void> Function(WidgetTester, _Cubit, _Repository, _Tcp) body,
|
||||
) {
|
||||
testWidgets(name, (tester) async {
|
||||
GetIt.I.registerSingleton<ILoggerService>(_Logger());
|
||||
RemoteControlDiagnostics.instance = RemoteControlDiagnostics(
|
||||
append: (_) async {},
|
||||
);
|
||||
final repo = _Repository();
|
||||
final tcp = _Tcp();
|
||||
emergency = _Emergency();
|
||||
_Status.reading = (
|
||||
sn: 'SN-1',
|
||||
active: false,
|
||||
receivedAt: tester.binding.clock.now(),
|
||||
);
|
||||
final cubit = _Cubit(repo, tcp, emergency);
|
||||
emergency.onReport = cubit.refreshEmergencyStatus;
|
||||
cubit.emit(
|
||||
cubit.state.copyWith(
|
||||
targetDevice: DeviceEntity(
|
||||
deviceName: 'SN-1',
|
||||
productId: 1,
|
||||
productName: '',
|
||||
tenantId: 1,
|
||||
tenantName: '',
|
||||
),
|
||||
),
|
||||
);
|
||||
try {
|
||||
cubit.refreshEmergencyStatus();
|
||||
await body(tester, cubit, repo, tcp);
|
||||
} finally {
|
||||
await cubit.close();
|
||||
await RemoteControlDiagnostics.instance.flush();
|
||||
await tcp.packets.close();
|
||||
await tester.pump(const Duration(seconds: 20));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await GetIt.I.reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> request(_Cubit c) =>
|
||||
c.requestControlPermissionS('SN-1', 'app', grabControl: true);
|
||||
void respond(
|
||||
_Tcp tcp,
|
||||
dynamic result, {
|
||||
String device = 'SN-1',
|
||||
String? reason,
|
||||
bool crc = true,
|
||||
}) {
|
||||
tcp.packets.add(
|
||||
RawPacket(
|
||||
command: 0x12,
|
||||
payload: Uint8List.fromList([
|
||||
...utf8.encode(
|
||||
jsonEncode({
|
||||
'respond': {
|
||||
'deviceId': device,
|
||||
'switchResult': result,
|
||||
'holder': 'you',
|
||||
if (reason != null) 'reason': reason,
|
||||
},
|
||||
}),
|
||||
),
|
||||
if (crc) ...[0, 0],
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
scenario('entry only queries and never sends', (t, c, r, tcp) async {
|
||||
await c.requestControlPermissionS('SN-1', 'app');
|
||||
expect(r.queries, 1);
|
||||
expect(r.sends, 0);
|
||||
expect(emergency.calls, isEmpty);
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle);
|
||||
});
|
||||
scenario('manual request sends once and blocks repeat taps', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await request(c);
|
||||
await request(c);
|
||||
expect(r.queries, 1);
|
||||
expect(r.sends, 1);
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_sent');
|
||||
expect(c.state.hasPermission, isFalse);
|
||||
});
|
||||
scenario('send notice waits for actual write completion', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
r.write = Completer<void>();
|
||||
final pending = request(c);
|
||||
await t.pump();
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.sending);
|
||||
expect(c.state.permissionFeedbackKey, isNot('permission_sent'));
|
||||
r.write!.complete();
|
||||
await pending;
|
||||
expect(c.state.permissionFeedbackKey, 'permission_sent');
|
||||
});
|
||||
scenario(
|
||||
'manual request with HTTP permission and no owner still sends once',
|
||||
(t, c, r, tcp) async {
|
||||
r.info = {'hasPermission': true, 'owner': null};
|
||||
await request(c);
|
||||
expect(r.sends, 1);
|
||||
expect(c.state.hasPermission, isFalse);
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting);
|
||||
respond(tcp, true);
|
||||
expect(c.state.hasPermission, isTrue);
|
||||
},
|
||||
);
|
||||
scenario('query errors preserve their classification and never send', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
r.queryError = ControlPermissionFailure('permission_query_invalid');
|
||||
await request(c);
|
||||
expect(r.sends, 0);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_query_invalid');
|
||||
expect(c.state.isPermissionRequestBusy, isFalse);
|
||||
});
|
||||
scenario('disconnected socket reports not sent', (t, c, r, tcp) async {
|
||||
tcp.connected = false;
|
||||
await request(c);
|
||||
expect(r.sends, 0);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_tcp_disconnected');
|
||||
});
|
||||
scenario('write failure reaches the UI', (t, c, r, tcp) async {
|
||||
r.sendError = ControlPermissionFailure('permission_send_uncertain');
|
||||
await request(c);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_send_uncertain');
|
||||
expect(c.state.isPermissionRequestBusy, isFalse);
|
||||
});
|
||||
scenario('matching success updates control and cancels timeout', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await request(c);
|
||||
respond(tcp, true);
|
||||
await t.pump();
|
||||
expect(c.state.hasPermission, isTrue);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_granted');
|
||||
await t.pump(const Duration(seconds: 11));
|
||||
expect(c.state.permissionFeedbackKey, 'permission_granted');
|
||||
});
|
||||
scenario('fast response cannot be overwritten by a late write completion', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
r.write = Completer<void>();
|
||||
final pending = request(c);
|
||||
await t.pump();
|
||||
respond(tcp, true);
|
||||
r.write!.complete();
|
||||
await pending;
|
||||
expect(c.state.hasPermission, isTrue);
|
||||
expect(c.state.permissionFeedbackKey, 'permission_granted');
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.granted);
|
||||
});
|
||||
scenario('wrong-device and invalid results cannot grant control', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await request(c);
|
||||
respond(tcp, true, device: 'SN-2');
|
||||
respond(tcp, null);
|
||||
await t.pump();
|
||||
expect(c.state.hasPermission, isFalse);
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.waiting);
|
||||
});
|
||||
scenario('explicit denial differs from a generic unsuccessful result', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await request(c);
|
||||
respond(tcp, false);
|
||||
await t.pump();
|
||||
expect(c.state.permissionFeedbackKey, 'permission_not_granted');
|
||||
expect(c.stops, 1);
|
||||
await request(c);
|
||||
respond(tcp, false, reason: 'holder_denied');
|
||||
await t.pump();
|
||||
expect(c.state.permissionFeedbackKey, 'permission_denied');
|
||||
});
|
||||
scenario('result without CRC is accepted', (t, c, r, tcp) async {
|
||||
await request(c);
|
||||
respond(tcp, true, crc: false);
|
||||
await t.pump();
|
||||
expect(c.state.hasPermission, isTrue);
|
||||
});
|
||||
scenario('no response times out and permits retry', (t, c, r, tcp) async {
|
||||
await request(c);
|
||||
await t.pump(const Duration(seconds: 11));
|
||||
expect(c.state.permissionFeedbackKey, 'permission_result_timeout');
|
||||
expect(c.state.hasPermission, isFalse);
|
||||
expect(c.state.isPermissionRequestBusy, isFalse);
|
||||
await request(c);
|
||||
expect(r.sends, 2);
|
||||
});
|
||||
scenario('disconnect while waiting is reported as unconfirmed', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await request(c);
|
||||
tcp.connected = false;
|
||||
await t.pump(const Duration(milliseconds: 250));
|
||||
expect(c.state.permissionFeedbackKey, 'permission_connection_lost');
|
||||
});
|
||||
scenario('exit invalidates an outstanding query and late TCP result', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
r.query = Completer<Map<String, dynamic>>();
|
||||
final pending = request(c);
|
||||
await t.pump();
|
||||
c.resetPermissionState();
|
||||
r.query!.complete({'hasPermission': true, 'owner': 'app'});
|
||||
await pending;
|
||||
respond(tcp, true);
|
||||
await t.pump();
|
||||
expect(c.state.hasPermission, isFalse);
|
||||
expect(c.state.permissionRequestPhase, PermissionRequestPhase.idle);
|
||||
expect(r.sends, 0);
|
||||
});
|
||||
scenario('query timeout cannot send a late request', (t, c, r, tcp) async {
|
||||
r.query = Completer<Map<String, dynamic>>();
|
||||
final pending = request(c);
|
||||
await t.pump(const Duration(seconds: 11));
|
||||
await pending;
|
||||
expect(c.state.permissionFeedbackKey, 'permission_query_timeout');
|
||||
r.query!.complete({'hasPermission': false, 'owner': 'web'});
|
||||
await t.pump();
|
||||
expect(r.sends, 0);
|
||||
});
|
||||
|
||||
scenario('e-stop uses current SN without TCP or control permission', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
tcp.connected = false;
|
||||
c.updateFunction(mower: 1, lift: 1);
|
||||
expect(await c.updateEmergency(true), isTrue);
|
||||
expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]);
|
||||
expect(r.motionSends, 0);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(c.state.isLocked, isTrue);
|
||||
expect(c.state.controlEntity.isEmergency, isFalse);
|
||||
expect(c.state.controlEntity.mowerSpeed, 0);
|
||||
expect(c.state.controlEntity.chassisLift, 0);
|
||||
expect(c.state.emergencyFeedbackKey, 'emergency_request_sent');
|
||||
});
|
||||
|
||||
scenario('release sends zero and clears local state only after API success', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await c.updateEmergency(true);
|
||||
emergency.pending = Completer<Either<Failure, Unit>>();
|
||||
final release = c.updateEmergency(false);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(c.state.isLocked, isTrue);
|
||||
expect(c.state.isEmergencyRequestPending, isTrue);
|
||||
// A late joystick callback must not revive old movement after release.
|
||||
c.updateFunction(mower: 0);
|
||||
emergency.pending!.complete(const Right(unit));
|
||||
expect(await release, isTrue);
|
||||
expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release));
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(c.state.isLocked, isFalse);
|
||||
expect(c.state.controlEntity.originX, 0);
|
||||
expect(c.state.controlEntity.originY, 0);
|
||||
expect(c.state.emergencyFeedbackKey, 'emergency_release_sent');
|
||||
expect(r.motionSends, 0);
|
||||
});
|
||||
|
||||
scenario('repeat taps and release while sending cannot duplicate requests', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
emergency.pending = Completer<Either<Failure, Unit>>();
|
||||
final first = c.updateEmergency(true);
|
||||
expect(await c.updateEmergency(true), isFalse);
|
||||
expect(await c.updateEmergency(false), isFalse);
|
||||
expect(emergency.calls, hasLength(1));
|
||||
emergency.pending!.complete(const Right(unit));
|
||||
await first;
|
||||
});
|
||||
|
||||
scenario('failed stop keeps local inhibit and permits retry', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
emergency.result = Left(NetworkFailure('timeout'));
|
||||
expect(await c.updateEmergency(true), isFalse);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(c.state.isLocked, isTrue);
|
||||
expect(c.state.emergencyRequestFailed, isTrue);
|
||||
emergency.result = const Right(unit);
|
||||
expect(await c.updateEmergency(true), isTrue);
|
||||
expect(emergency.calls, hasLength(2));
|
||||
});
|
||||
|
||||
scenario('business failure during stop keeps normal UI and permits retry', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
c.emit(c.state.copyWith(hasPermission: true));
|
||||
c.startControlLoop();
|
||||
emergency.pending = Completer<Either<Failure, Unit>>();
|
||||
final sending = c.updateEmergency(true);
|
||||
expect(c.state.isEmergencyRequestPending, isTrue);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
c.toggleLock();
|
||||
await t.pump(const Duration(milliseconds: 200));
|
||||
expect(r.motionSends, 0);
|
||||
emergency.pending!.complete(Left(EmergencyStopRejectedFailure('设备模式切换失败')));
|
||||
expect(await sending, isFalse);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(c.state.isLocked, isFalse);
|
||||
expect(c.state.isEmergencyRequestPending, isFalse);
|
||||
expect(c.state.emergencyFeedbackKey, 'emergency_request_rejected');
|
||||
emergency.pending = null;
|
||||
expect(await c.updateEmergency(true), isTrue);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
});
|
||||
|
||||
scenario('business failure during release keeps previous e-stop state', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await c.updateEmergency(true);
|
||||
emergency.result = Left(EmergencyStopRejectedFailure('设备模式切换失败'));
|
||||
expect(await c.updateEmergency(false), isFalse);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(c.state.isLocked, isTrue);
|
||||
expect(c.state.isEmergencyRequestPending, isFalse);
|
||||
expect(c.state.emergencyRequestFailed, isTrue);
|
||||
});
|
||||
|
||||
scenario('missing SN does not send an e-stop request', (t, c, r, tcp) async {
|
||||
c.clearTargetDevice();
|
||||
expect(await c.updateEmergency(true), isFalse);
|
||||
expect(emergency.calls, isEmpty);
|
||||
expect(c.state.emergencyFeedbackKey, 'emergency_missing_sn');
|
||||
});
|
||||
|
||||
scenario('exiting session does not request release or clear local e-stop', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await c.updateEmergency(true);
|
||||
c.resetPermissionState();
|
||||
expect(emergency.calls, hasLength(1));
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(c.state.isLocked, isTrue);
|
||||
});
|
||||
|
||||
scenario('late e-stop reply cannot apply after target was cleared', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
emergency.pending = Completer<Either<Failure, Unit>>();
|
||||
final pending = c.updateEmergency(true);
|
||||
c.clearTargetDevice();
|
||||
emergency.pending!.complete(const Right(unit));
|
||||
expect(await pending, isFalse);
|
||||
expect(c.state.targetDevice, isNull);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(c.state.isEmergencyRequestPending, isFalse);
|
||||
});
|
||||
|
||||
scenario('motion loop waits 250ms and sends the latest input', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
c.emit(c.state.copyWith(hasPermission: true));
|
||||
c.startControlLoop();
|
||||
c.updateOriginY(25);
|
||||
await t.pump(const Duration(milliseconds: 200));
|
||||
expect(r.sentFrames, isEmpty);
|
||||
c.updateOriginY(75);
|
||||
await t.pump(const Duration(milliseconds: 49));
|
||||
expect(r.sentFrames, isEmpty);
|
||||
await t.pump(const Duration(milliseconds: 1));
|
||||
expect(r.sentFrames.map((frame) => frame.originY), [75]);
|
||||
c.updateOriginY(50);
|
||||
await t.pump(const Duration(milliseconds: 250));
|
||||
expect(r.sentFrames.map((frame) => frame.originY), [75, 50]);
|
||||
});
|
||||
|
||||
scenario('mower hold repeats every 250ms and release keeps last operation', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
expect(c.state.controlEntity.mowerSpeed, 2);
|
||||
c.emit(c.state.copyWith(hasPermission: true));
|
||||
c.startControlLoop();
|
||||
c.sendMowerSliderCommand(1);
|
||||
await t.pump(const Duration(milliseconds: 750));
|
||||
expect(r.sentFrames.map((frame) => frame.mowerSpeed), [1, 1, 1]);
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.turnOn);
|
||||
c.sendMowerSliderCommand(0);
|
||||
await t.pump(const Duration(milliseconds: 250));
|
||||
expect(r.sentFrames.last.mowerSpeed, 2);
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.turnOn);
|
||||
c.sendMowerSliderCommand(2);
|
||||
await t.pump(const Duration(milliseconds: 250));
|
||||
expect(r.sentFrames.last.mowerSpeed, 0);
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.turnOff);
|
||||
c.sendMowerSliderCommand(0);
|
||||
await t.pump(const Duration(milliseconds: 250));
|
||||
expect(r.sentFrames.last.mowerSpeed, 2);
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.turnOff);
|
||||
expect(c.state.controlEntity.chassisLift, 0);
|
||||
expect(c.state.controlEntity.ignitionStatus, 0);
|
||||
});
|
||||
|
||||
scenario('mower session reset clears last operation and pending command', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
c.sendMowerSliderCommand(1);
|
||||
c.resetPermissionState();
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.none);
|
||||
expect(c.state.controlEntity.mowerSpeed, 2);
|
||||
c.sendMowerSliderCommand(2);
|
||||
c.resetMowerControl();
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.none);
|
||||
expect(c.state.controlEntity.mowerSpeed, 2);
|
||||
c.sendMowerSliderCommand(1);
|
||||
c.clearTargetDevice();
|
||||
expect(c.state.targetDevice, isNull);
|
||||
expect(c.state.lastMowerOperation, MowerLastOperation.none);
|
||||
expect(c.state.controlEntity.mowerSpeed, 2);
|
||||
});
|
||||
|
||||
scenario('telemetry controls UI and API success cannot change it', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
emergency.autoReport = false;
|
||||
expect(c.state.hasEmergencyStatus, isTrue);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(await c.updateEmergency(true), isTrue);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
_Status.reading = (
|
||||
sn: 'SN-1',
|
||||
active: true,
|
||||
receivedAt: t.binding.clock.now(),
|
||||
);
|
||||
c.refreshEmergencyStatus();
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(await c.updateEmergency(true), isFalse);
|
||||
expect(emergency.calls, hasLength(1));
|
||||
expect(await c.updateEmergency(false), isTrue);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
_Status.reading = (
|
||||
sn: 'SN-1',
|
||||
active: false,
|
||||
receivedAt: t.binding.clock.now(),
|
||||
);
|
||||
c.refreshEmergencyStatus();
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
});
|
||||
|
||||
scenario('telemetry missing stale or from another SN blocks commands', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
for (final reading in <({String sn, bool? active, DateTime receivedAt})?>[
|
||||
null,
|
||||
(sn: 'SN-1', active: null, receivedAt: t.binding.clock.now()),
|
||||
(sn: 'SN-2', active: false, receivedAt: t.binding.clock.now()),
|
||||
(
|
||||
sn: 'SN-1',
|
||||
active: false,
|
||||
receivedAt: t.binding.clock.now().subtract(const Duration(seconds: 11)),
|
||||
),
|
||||
]) {
|
||||
_Status.reading = reading;
|
||||
c.refreshEmergencyStatus();
|
||||
expect(c.state.hasEmergencyStatus, isFalse);
|
||||
expect(await c.updateEmergency(true), isFalse);
|
||||
expect(await c.updateEmergency(false), isFalse);
|
||||
}
|
||||
expect(emergency.calls, isEmpty);
|
||||
});
|
||||
|
||||
Future<void> mountButton(WidgetTester t, _Cubit c) async {
|
||||
final translations = AppLocalizations(AppLocalizations.english);
|
||||
await t.runAsync(translations.load);
|
||||
await t.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: [_LoadedLocalizations(translations)],
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: AppLocalizations.english,
|
||||
home: BlocProvider<RemoteControlCubit>.value(
|
||||
value: c,
|
||||
child: Scaffold(
|
||||
body: BlocBuilder<RemoteControlCubit, RemoteControlState>(
|
||||
builder: (context, state) => Stack(
|
||||
children: [
|
||||
if (state.isEmergency)
|
||||
const Positioned.fill(child: EmergencyOverlay()),
|
||||
const Center(child: EmergencyStopButton(width: 180)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await t.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> confirmDialog(WidgetTester t) async {
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
await t.tap(find.byKey(const ValueKey('emergency-confirm')));
|
||||
await t.pump();
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
}
|
||||
|
||||
scenario('button confirmation sends stop and release and removes breathing', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await mountButton(t, c);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump();
|
||||
expect(emergency.calls, isEmpty);
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
await confirmDialog(t);
|
||||
await t.pump();
|
||||
expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]);
|
||||
expect(find.byType(EmergencyOverlay), findsOneWidget);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump();
|
||||
expect(emergency.calls, hasLength(1));
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
await confirmDialog(t);
|
||||
expect(emergency.calls.last, ('SN-1', EmergencyStopTarget.release));
|
||||
expect(emergency.calls, hasLength(2));
|
||||
expect(find.byType(EmergencyOverlay), findsNothing);
|
||||
expect(r.motionSends, 0);
|
||||
});
|
||||
|
||||
scenario(
|
||||
'cancel stop confirmation sends nothing and does not start breathing',
|
||||
(t, c, r, tcp) async {
|
||||
await mountButton(t, c);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
expect(emergency.calls, isEmpty);
|
||||
await t.tap(find.byKey(const ValueKey('emergency-cancel')));
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
expect(emergency.calls, isEmpty);
|
||||
expect(c.state.isEmergency, isFalse);
|
||||
expect(find.byType(EmergencyOverlay), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
scenario('cancel release confirmation keeps e-stop without sending zero', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await mountButton(t, c);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump();
|
||||
await confirmDialog(t);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
await t.tap(find.byKey(const ValueKey('emergency-cancel')));
|
||||
await t.pump(const Duration(milliseconds: 400));
|
||||
expect(emergency.calls, [('SN-1', EmergencyStopTarget.engage)]);
|
||||
expect(c.state.isEmergency, isTrue);
|
||||
expect(find.byType(EmergencyOverlay), findsOneWidget);
|
||||
});
|
||||
|
||||
scenario('changing target while confirming never sends to another vehicle', (
|
||||
t,
|
||||
c,
|
||||
r,
|
||||
tcp,
|
||||
) async {
|
||||
await mountButton(t, c);
|
||||
await t.tap(find.byType(EmergencyStopButton));
|
||||
await t.pump();
|
||||
c.clearTargetDevice();
|
||||
await confirmDialog(t);
|
||||
expect(emergency.calls, isEmpty);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user