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