完善遥控权限、控制发送和急停反馈
This commit is contained in:
@@ -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(' ')}',
|
||||
|
||||
Reference in New Issue
Block a user