对接远程遥控
This commit is contained in:
@@ -27,19 +27,23 @@ class RemoteHttpDatasource {
|
||||
}*/
|
||||
|
||||
|
||||
Future<bool> requestRemoteControlViaHttp( String deviceId, String currentDeviceId) async {
|
||||
/// 🔥 返回完整权限信息: {hasPermission, owner}
|
||||
Future<Map<String, dynamic>> requestRemoteControlViaHttp(String deviceName, String platform) async {
|
||||
print(deviceName+"@@@");
|
||||
final user = await _userStorage.getUser();
|
||||
if (user == null) {
|
||||
debugPrint('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限');
|
||||
_logger.log('❌ [RemoteHttp] 用户未登录,无法请求远程控制权限');
|
||||
return false;
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
}
|
||||
final token = user.token;
|
||||
|
||||
debugPrint('🔑 [RemoteHttp] 开始请求远程控制权限 - deviceId: $deviceId, platform: app');
|
||||
_logger.log('🔑 [RemoteHttp] 开始请求远程控制权限 - deviceId: $deviceId, platform: app');
|
||||
debugPrint('🔑 [RemoteHttp] 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform');
|
||||
_logger.log('🔑 [RemoteHttp] 开始请求远程控制权限 - deviceName: $deviceName, platform: $platform');
|
||||
|
||||
try {
|
||||
debugPrint('📡 [RemoteHttp] 正在发送 HTTP POST 请求到 /forward/device/remoteControl');
|
||||
debugPrint('📡 [RemoteHttp] 请求参数: deviceId=$deviceName, platform=$platform');
|
||||
final response = await _dio.post(
|
||||
'/forward/device/remoteControl',
|
||||
options: Options(
|
||||
@@ -48,7 +52,8 @@ class RemoteHttpDatasource {
|
||||
'Authorization': 'Bearer ${token}',
|
||||
},
|
||||
),
|
||||
data: {'deviceId': deviceId, 'platform': "app"});
|
||||
data: {'deviceId': deviceName, 'platform': platform});
|
||||
debugPrint('📥 [RemoteHttp] HTTP 请求已发送,等待响应...');
|
||||
|
||||
debugPrint("📊 [RemoteHttp] HTTP响应状态码: ${response.statusCode}");
|
||||
_logger.log("📊 [RemoteHttp] HTTP响应状态码: ${response.statusCode}");
|
||||
@@ -57,24 +62,25 @@ class RemoteHttpDatasource {
|
||||
debugPrint("📊 [RemoteHttp] 完整响应数据:$responseData");
|
||||
_logger.log("📊 [RemoteHttp] 完整响应数据:$responseData");
|
||||
|
||||
// 🔥 关键:先获取响应的 data 字段,再获取 remoteControl
|
||||
// 🔥 关键:先获取响应的 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("✅ [RemoteHttp] 解析成功 - remoteControl=$hasRemoteControl");
|
||||
_logger.log("✅ [RemoteHttp] 解析成功 - remoteControl=$hasRemoteControl");
|
||||
// 🔥 直接返回 remoteControl 的布尔值
|
||||
return hasRemoteControl;
|
||||
debugPrint("✅ [RemoteHttp] 解析成功 - remoteControl=$hasRemoteControl, owner=$owner");
|
||||
_logger.log("✅ [RemoteHttp] 解析成功 - remoteControl=$hasRemoteControl, owner=$owner");
|
||||
// 🔥 返回完整权限信息
|
||||
return {'hasPermission': hasRemoteControl, 'owner': owner};
|
||||
} else {
|
||||
debugPrint("❌ [RemoteHttp] 缺少 data 字段,响应结构异常");
|
||||
_logger.log("❌ [RemoteHttp] 缺少 data 字段,响应结构异常");
|
||||
return false;
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [RemoteHttp] 请求远程控制权限失败:$e');
|
||||
_logger.log('❌ [RemoteHttp] 请求远程控制权限失败:$e');
|
||||
return false;
|
||||
return {'hasPermission': false, 'owner': null};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@ import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/protocol/machine_protocol_constants.dart';
|
||||
@@ -14,11 +16,12 @@ import '../../../../core/storage/user_storage.dart';
|
||||
class RemoteTcpDatasource {
|
||||
final TcpClient _tcpClient;
|
||||
final UserStorage _userStorage;
|
||||
final ILoggerService _logger = GetIt.I<ILoggerService>();
|
||||
|
||||
RemoteTcpDatasource(this._tcpClient, this._userStorage);
|
||||
|
||||
/// 发送 switch_control 权限请求(对应 Android 的 requestSwitchControl)
|
||||
///
|
||||
///
|
||||
/// 这是获取设备控制权的第一步:
|
||||
/// 1. 先发送 TCP 0x12 指令携带 switch_control 请求
|
||||
/// 2. 等待服务端响应
|
||||
@@ -33,7 +36,9 @@ class RemoteTcpDatasource {
|
||||
// 获取用户信息
|
||||
final user = await _userStorage.getUser();
|
||||
if (user == null || user.token == null) {
|
||||
debugPrint('❌ sendSwitchControlRequest[TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包');
|
||||
debugPrint(
|
||||
'❌ sendSwitchControlRequest[TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包',
|
||||
);
|
||||
throw Exception('用户未登录或 Token 无效');
|
||||
}
|
||||
|
||||
@@ -66,12 +71,16 @@ class RemoteTcpDatasource {
|
||||
// 构造完整的协议包
|
||||
final packet = buildSwitchControlPacket(jsonBytes);
|
||||
|
||||
debugPrint('sendSwitchControlRequest[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}');
|
||||
debugPrint(
|
||||
'sendSwitchControlRequest[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}',
|
||||
);
|
||||
|
||||
// 发送数据包
|
||||
_tcpClient.sendnew(packet);
|
||||
|
||||
debugPrint('✅ sendSwitchControlRequest[TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})');
|
||||
debugPrint(
|
||||
'✅ sendSwitchControlRequest[TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('❌ sendSwitchControlRequest[TCP] 发送权限请求失败:$e');
|
||||
rethrow;
|
||||
@@ -105,51 +114,108 @@ class RemoteTcpDatasource {
|
||||
|
||||
return builder.takeBytes();
|
||||
}
|
||||
// TODO: 同意授权和拒绝授权
|
||||
void sendSwitchControlResponse(bool bool, String deviceId) {
|
||||
|
||||
// TODO: 同意授权和拒绝授权
|
||||
void sendSwitchControlResponse(bool agreed, String deviceId) {
|
||||
debugPrint(
|
||||
'📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId',
|
||||
);
|
||||
|
||||
// 🔥 添加详细的连接状态日志
|
||||
debugPrint(
|
||||
'📤 [进入了TCP层==== 当前 TCP 连接状态: isConnected=${_tcpClient.isConnected}',
|
||||
);
|
||||
|
||||
if (!_tcpClient.isConnected) {
|
||||
debugPrint('❌sendSwitchControlResponse [TCP] 无法发送权限响应:Socket 未连接');
|
||||
debugPrint('❌ [TCP DataSource] 无法发送权限响应: Socket 未连接');
|
||||
debugPrint('❌ [TCP DataSource] isConnected=${_tcpClient.isConnected}');
|
||||
throw Exception('sendSwitchControlResponse TCP 未连接');
|
||||
}
|
||||
|
||||
try {
|
||||
// 构造响应 JSON(参考 Android 代码)
|
||||
final response = bool
|
||||
? {
|
||||
'respond': {
|
||||
'switchResult': true,
|
||||
'deviceId': deviceId,
|
||||
'holder': 'you',
|
||||
},
|
||||
}
|
||||
: {
|
||||
'respond': {
|
||||
'switchResult': false,
|
||||
'deviceId': deviceId,
|
||||
'reason': 'holder_denied',
|
||||
},
|
||||
};
|
||||
debugPrint('📡 [TCP DataSource] TCP 连接正常,准备发送数据...');
|
||||
|
||||
if(!bool){
|
||||
debugPrint('sendSwitchControlResponse[TCP] 拒绝授权:$deviceId');
|
||||
}else{
|
||||
debugPrint('sendSwitchControlResponse[TCP] 同意授权:$deviceId');
|
||||
}
|
||||
//debugPrint('sendSwitchControlResponse[TCP] 同意授权:$deviceId');
|
||||
final jsonStr = jsonEncode(response);
|
||||
final jsonBytes = utf8.encode(jsonStr);
|
||||
// 构造响应 JSON(参考 Android 代码)
|
||||
final response = agreed
|
||||
? {
|
||||
'respond': {
|
||||
'switchResult': true,
|
||||
'deviceId': deviceId,
|
||||
'holder': 'you',
|
||||
},
|
||||
}
|
||||
: {
|
||||
'respond': {
|
||||
'switchResult': false,
|
||||
'deviceId': deviceId,
|
||||
'reason': 'holder_denied',
|
||||
},
|
||||
};
|
||||
|
||||
debugPrint('sendSwitchControlResponse[TCP] 响应权限请求:$jsonStr');
|
||||
debugPrint(
|
||||
'📝 [TCP DataSource] ${agreed ? "同意" : "拒绝"}授权: deviceId=$deviceId',
|
||||
);
|
||||
|
||||
// 构造完整的协议包
|
||||
final packet = buildSwitchControlPacket(jsonBytes);
|
||||
final jsonStr = jsonEncode(response);
|
||||
final jsonBytes = utf8.encode(jsonStr);
|
||||
|
||||
debugPrint('sendSwitchControlResponse[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}');
|
||||
debugPrint('📦 [TCP DataSource] JSON 数据: $jsonStr');
|
||||
debugPrint('📦 [TCP DataSource] JSON 字节长度: ${jsonBytes.length} 字节');
|
||||
|
||||
// 发送数据包
|
||||
_tcpClient.sendnew(packet);
|
||||
}
|
||||
catch (e) {
|
||||
debugPrint('❌ sendSwitchControlResponse[TCP] 响应权限请求失败:$e');
|
||||
// 构造完整的协议包
|
||||
final packet = buildSwitchControlPacket(jsonBytes);
|
||||
|
||||
_logger.logWithLevel('TCP DataSource] JSON 数据: $jsonStr' ,shouldLog: true);
|
||||
|
||||
debugPrint(
|
||||
'📦 [TCP DataSource] 完整数据包(${packet.length}字节): ${packet.map((b) => '0x${b.toRadixString(16).padLeft(2, "0")}').join(' ')}',
|
||||
);
|
||||
|
||||
// 🔥 发送前再次检查连接状态
|
||||
if (!_tcpClient.isConnected) {
|
||||
debugPrint('❌ [TCP DataSource] 发送前检查: Socket 已断开连接!');
|
||||
throw Exception('TCP 连接在发送前断开');
|
||||
}
|
||||
|
||||
// 发送数据包
|
||||
debugPrint('🚀 [TCP DataSource] 正在调用 SendNew 发送数据...');
|
||||
|
||||
// 🔥 添加详细日志:记录发送的完整数据包(十六进制)
|
||||
final hexString = packet
|
||||
.map((byte) => '0x${byte.toRadixString(16).padLeft(2, '0')}')
|
||||
.join(' ');
|
||||
debugPrint('📦 [TCP DataSource] 完整数据包(${packet.length}字节): $hexString');
|
||||
|
||||
// 🔥 使用ILoggerService记录日志
|
||||
_logger.logWithLevel(
|
||||
'📦 [TCP DataSource] 完整数据包(${packet.length}字节): $hexString',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
// 🔥 记录JSON内容和字节数
|
||||
_logger.logWithLevel(
|
||||
'📝 [TCP DataSource] 发送内容: $jsonStr',
|
||||
shouldLog: true,
|
||||
);
|
||||
_logger.logWithLevel(
|
||||
'📊 [TCP DataSource] JSON字节数: ${jsonBytes.length}, 完整包字节数: ${packet.length}',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
_tcpClient.sendnew(packet);
|
||||
|
||||
debugPrint('✅ [TCP DataSource] TCP 响应已成功发送');
|
||||
debugPrint('✅ [TCP DataSource] 发送字节数: ${packet.length}');
|
||||
|
||||
// 🔥 发送成功后的日志
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP DataSource] TCP 响应已成功发送 - agreed=$agreed, deviceId=$deviceId, 字节数=${packet.length}',
|
||||
shouldLog: true,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP DataSource] 响应权限请求失败: $e');
|
||||
debugPrint('❌ [TCP DataSource] 错误类型: ${e.runtimeType}');
|
||||
debugPrint('❌ [TCP DataSource] 错误堆栈: ${StackTrace.current}');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
@@ -19,11 +18,15 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
final TcpClient _tcpClient;
|
||||
final DiffSteerUseCase _diffSteer;
|
||||
final RemoteHttpDatasource _remoteHttp;
|
||||
final RemoteTcpDatasource _remoteTcp;
|
||||
final RemoteTcpDatasource _remoteTcp;
|
||||
final ILoggerService _logger = GetIt.I<ILoggerService>();
|
||||
|
||||
|
||||
RemoteControlRepositoryImpl(this._tcpClient, this._diffSteer, this._remoteHttp, this._remoteTcp);
|
||||
RemoteControlRepositoryImpl(
|
||||
this._tcpClient,
|
||||
this._diffSteer,
|
||||
this._remoteHttp,
|
||||
this._remoteTcp,
|
||||
);
|
||||
|
||||
@override
|
||||
void changeWebViewDirection(String direction) {
|
||||
@@ -34,7 +37,9 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
void sendControlMachineCmd(MachineControlStatusEntity status) {
|
||||
// 1. 调用算法:将摇杆坐标 (x, y) 转换为左右轮电机转速
|
||||
final speeds = _diffSteer.calculate(status.originX, status.originY);
|
||||
_logger.logWithLevel('⚙️ [电机速度] left: ${speeds['left']}, right: ${speeds['right']}');
|
||||
_logger.logWithLevel(
|
||||
'⚙️ [电机速度] left: ${speeds['left']}, right: ${speeds['right']}',
|
||||
);
|
||||
|
||||
// 2. 调用 Codec:生成协议要求的 8 字节 Payload
|
||||
final payload = MachineProtocolCodec.encodeRemoteControlPayload(
|
||||
@@ -45,41 +50,104 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
ignition: status.ignitionStatus,
|
||||
emergency: status.isEmergency ? 1 : 0,
|
||||
);
|
||||
|
||||
|
||||
// 3. 调用 TcpClient 发送指令
|
||||
_tcpClient.sendRaw(
|
||||
MachineProtocolConstants.cmdRemoteControl,
|
||||
payload,
|
||||
);
|
||||
_tcpClient.sendRaw(MachineProtocolConstants.cmdRemoteControl, payload);
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<RawPacket> get responseStream => _tcpClient.packetStream;
|
||||
|
||||
@override
|
||||
Future<bool> requestControlPermission( String deviceName, String deviceId) async {
|
||||
void sendTcpPermissionRequest(String deviceName) {
|
||||
_remoteTcp.sendSwitchControlRequest(deviceName);
|
||||
_logger.logWithLevel('🔑 [RemoteControl] TCP已发送权限请求');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> requestControlPermission(
|
||||
String deviceName,
|
||||
String deviceId,
|
||||
) async {
|
||||
try {
|
||||
_remoteTcp.sendSwitchControlRequest(deviceName);
|
||||
// debugPrint('🔑 [RemoteControl] TCP已发送权限请求');
|
||||
_logger.logWithLevel('🔑 [RemoteControl] TCP已发送权限请求');
|
||||
return await _remoteHttp.requestRemoteControlViaHttp(deviceName, deviceId);
|
||||
// 1. 先发送 HTTP 权限请求检查权限
|
||||
_logger.logWithLevel('🔑 [RemoteControl] 检查 HTTP 权限...');
|
||||
final result = await _remoteHttp.requestRemoteControlViaHttp(
|
||||
deviceName,
|
||||
deviceId,
|
||||
);
|
||||
|
||||
// 2. 如果没有权限或权限为 null,才发送 TCP 请求
|
||||
final hasPermission = result['hasPermission'] as bool? ?? false;
|
||||
if (!hasPermission) {
|
||||
_logger.logWithLevel('🔑 [RemoteControl] 无权限,发送 TCP 权限请求');
|
||||
_remoteTcp.sendSwitchControlRequest(deviceName);
|
||||
} else {
|
||||
_logger.logWithLevel('✅ [RemoteControl] 已有权限,无需 TCP 请求');
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
//sdebugPrint('❌ [RemoteControl] 权限请求失败:$e');
|
||||
_logger.logWithLevel('❌ [RemoteControl] 权限请求失败:$e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void respondPermission(bool bool, String deviceId) {
|
||||
// TODO: implement respondPermission
|
||||
if (bool) {
|
||||
_remoteTcp.sendSwitchControlResponse(true, deviceId);
|
||||
} else {
|
||||
_remoteTcp.sendSwitchControlResponse(false, deviceId);
|
||||
void respondPermission(bool agreed, String deviceId) {
|
||||
final timePrefix = DateTime.now().toIso8601String();
|
||||
final logPrefix = '$timePrefix 📤 [RemoteControlRepository]';
|
||||
|
||||
debugPrint('$logPrefix =========================================');
|
||||
debugPrint('$logPrefix respondPermission 被调用');
|
||||
debugPrint('$logPrefix agreed: $agreed, deviceId: $deviceId');
|
||||
_logger.logWithLevel(
|
||||
'$logPrefix respondPermission 被调用 - agreed=$agreed, deviceId=$deviceId',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
try {
|
||||
// 🔥 检查 _remoteTcp 是否为空
|
||||
if (_remoteTcp == null) {
|
||||
debugPrint('$logPrefix ❌ _remoteTcp 为空,无法发送 TCP 指令');
|
||||
_logger.logWithLevel('$logPrefix ❌ _remoteTcp 为空', shouldLog: true);
|
||||
throw Exception('_remoteTcp 为空');
|
||||
}
|
||||
|
||||
// 🔥 检查 TCP 连接状态
|
||||
debugPrint('$logPrefix 📡 TCP连接状态: ${_remoteTcp.isConnected}');
|
||||
_logger.logWithLevel(
|
||||
'$logPrefix 📡 TCP连接状态: ${_remoteTcp.isConnected}',
|
||||
shouldLog: true,
|
||||
);
|
||||
|
||||
if (agreed) {
|
||||
debugPrint('$logPrefix ✅ 用户同意释放权限,发送同意响应');
|
||||
_logger.logWithLevel('$logPrefix ✅ 准备发送同意响应 TCP 指令', shouldLog: true);
|
||||
_remoteTcp.sendSwitchControlResponse(true, deviceId);
|
||||
} else {
|
||||
debugPrint('$logPrefix ❌ 用户拒绝释放权限,发送拒绝响应');
|
||||
_logger.logWithLevel('$logPrefix ❌ 准备发送拒绝响应 TCP 指令', shouldLog: true);
|
||||
_remoteTcp.sendSwitchControlResponse(false, deviceId);
|
||||
}
|
||||
|
||||
debugPrint('$logPrefix ✅ TCP 响应发送完成');
|
||||
_logger.logWithLevel('$logPrefix ✅ TCP 响应发送完成', shouldLog: true);
|
||||
} catch (e) {
|
||||
debugPrint('$logPrefix ❌ respondPermission 失败: $e');
|
||||
debugPrint('$logPrefix ❌ 错误类型: ${e.runtimeType}');
|
||||
_logger.logWithLevel(
|
||||
'$logPrefix ❌ respondPermission 失败: $e',
|
||||
shouldLog: true,
|
||||
);
|
||||
// 🔥 关键修复:重新抛出异常,让上层知道 TCP 发送失败了
|
||||
rethrow;
|
||||
}
|
||||
|
||||
debugPrint('$logPrefix =========================================');
|
||||
}
|
||||
///app退出远程控制后释放权限
|
||||
|
||||
///app退出远程控制后释放权限
|
||||
@override
|
||||
Future<bool> releasePermission(String platform) async {
|
||||
return await _remoteHttp.releaseRemoteControlViaHttp(platform);
|
||||
|
||||
Reference in New Issue
Block a user