From c0bf6a7a41aef7d729cf78087c95d6cb3e0c72a5 Mon Sep 17 00:00:00 2001 From: Songzex <2402265378@qq.com> Date: Mon, 16 Mar 2026 15:31:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90web=E5=92=8Capp=E6=9D=83?= =?UTF-8?q?=E9=99=90=E4=BA=A4=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../datasources/remote_tcp_datasource.dart | 98 +++++++++++++++++-- .../remote_control_repository_impl.dart | 14 ++- .../remote_control_repository.dart | 2 + .../bloc/remote_control_cubit.dart | 79 ++++++++++++--- .../pages/remote_control_page.dart | 23 ++++- 5 files changed, 189 insertions(+), 27 deletions(-) diff --git a/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart b/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart index c5be989f..b567b00a 100644 --- a/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart +++ b/lib/features/remote_control/data/datasources/remote_tcp_datasource.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:typed_data'; import 'package:flutter/material.dart'; @@ -24,15 +25,15 @@ class RemoteTcpDatasource { /// 3. 再调用 HTTP API 确认控制权 Future sendSwitchControlRequest(String deviceName) async { if (!_tcpClient.isConnected) { - debugPrint('❌ [TCP] 无法发送权限请求:Socket 未连接'); - throw Exception('TCP 未连接'); + debugPrint('❌sendSwitchControlRequest [TCP] 无法发送权限请求:Socket 未连接'); + throw Exception('sendSwitchControlRequest TCP 未连接'); } try { // 获取用户信息 final user = await _userStorage.getUser(); if (user == null || user.token == null) { - debugPrint('❌ [TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包'); + debugPrint('❌ sendSwitchControlRequest[TCP] 认证失败:用户未登录或 Token 为空,无法发送认证包'); throw Exception('用户未登录或 Token 无效'); } @@ -52,19 +53,27 @@ class RemoteTcpDatasource { final jsonStr = jsonEncode(request); final jsonBytes = utf8.encode(jsonStr); - debugPrint('🔑 [TCP] 发送权限请求:$jsonStr'); + debugPrint('sendSwitchControlRequest[TCP] 发送权限请求指令:$jsonStr'); + debugPrint('sendSwitchControlRequest[TCP] 发送权限请求指令:$jsonBytes'); // 使用 0x12 指令发送(cmdGetAuth) // 注意:根据你的协议文档,这里可能是 0x04 或 0x12 // Android 代码中使用的是 0x12 - _tcpClient.sendRaw( - MachineProtocolConstants.cmdGetAuth, // 0x04 或 0x12,根据实际协议调整 - jsonBytes, - ); + // _tcpClient.sendnew( + // // MachineProtocolConstants.cmdGetAuth, // 0x04 或 0x12,根据实际协议调整 + // jsonBytes, + // ); + // 构造完整的协议包 + final packet = buildSwitchControlPacket(jsonBytes); - debugPrint('✅ [TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})'); + debugPrint('sendSwitchControlRequest[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}'); + + // 发送数据包 + _tcpClient.sendnew(packet); + + debugPrint('✅ sendSwitchControlRequest[TCP] 已发送 switch_control 权限请求 (0x${MachineProtocolConstants.cmdGetAuth.toRadixString(16)})'); } catch (e) { - debugPrint('❌ [TCP] 发送权限请求失败:$e'); + debugPrint('❌ sendSwitchControlRequest[TCP] 发送权限请求失败:$e'); rethrow; } } @@ -75,4 +84,73 @@ class RemoteTcpDatasource { /// 检查 TCP 连接状态 bool get isConnected => _tcpClient.isConnected; + + /// 构建 switch_control 协议包 + /// + /// 包结构: + /// - 帧头:0xAB, 0xAA (2 字节) + /// - 命令字:0x12 (1 字节) + /// - 数据载荷:JSON UTF-8 字节 (N 字节) + /// - 帧尾:0x00, 0x00, 0xAA, 0xAB (4 字节) + List buildSwitchControlPacket(List jsonBytes) { + final builder = BytesBuilder() + ..addByte(MachineProtocolConstants.header1) // 0xAB + ..addByte(MachineProtocolConstants.header2) // 0xAA + ..addByte(0x12) // 命令字:switch_control + ..add(jsonBytes) // JSON 数据 + ..addByte(0x00) // CRC 占位 1 + ..addByte(0x00) // CRC 占位 2 + ..addByte(MachineProtocolConstants.endFlag1) // 0xAA + ..addByte(MachineProtocolConstants.endFlag2); // 0xAB + + return builder.takeBytes(); + } +// TODO: 同意授权和拒绝授权 + void sendSwitchControlResponse(bool bool, String deviceId) { + if (!_tcpClient.isConnected) { + debugPrint('❌sendSwitchControlResponse [TCP] 无法发送权限响应:Socket 未连接'); + 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', + }, + }; + + if(!bool){ + debugPrint('sendSwitchControlResponse[TCP] 拒绝授权:$deviceId'); + }else{ + debugPrint('sendSwitchControlResponse[TCP] 同意授权:$deviceId'); + } + //debugPrint('sendSwitchControlResponse[TCP] 同意授权:$deviceId'); + final jsonStr = jsonEncode(response); + final jsonBytes = utf8.encode(jsonStr); + + debugPrint('sendSwitchControlResponse[TCP] 响应权限请求:$jsonStr'); + + // 构造完整的协议包 + final packet = buildSwitchControlPacket(jsonBytes); + + debugPrint('sendSwitchControlResponse[TCP] 完整数据包:${packet.map((b) => '0x${b.toRadixString(16)}').join(' ')}'); + + // 发送数据包 + _tcpClient.sendnew(packet); + } + catch (e) { + debugPrint('❌ sendSwitchControlResponse[TCP] 响应权限请求失败:$e'); + rethrow; + } + } } diff --git a/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart b/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart index c91d8583..666ac143 100644 --- a/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart +++ b/lib/features/remote_control/data/repositories/remote_control_repository_impl.dart @@ -63,12 +63,22 @@ class RemoteControlRepositoryImpl implements RemoteControlRepository { @override Future requestControlPermission( String deviceName, String deviceId) async { try { - await _remoteTcp.sendSwitchControlRequest(deviceName); - debugPrint('🔑 [RemoteControl] TCP已发送权限请求 (0x04)'); + _remoteTcp.sendSwitchControlRequest(deviceName); + debugPrint('🔑 [RemoteControl] TCP已发送权限请求'); return await _remoteHttp.requestRemoteControlViaHttp(deviceName, deviceId); } catch (e) { debugPrint('❌ [RemoteControl] 权限请求失败:$e'); rethrow; } } + + @override + void respondPermission(bool bool, String deviceId) { + // TODO: implement respondPermission + if (bool) { + _remoteTcp.sendSwitchControlResponse(true, deviceId); + } else { + _remoteTcp.sendSwitchControlResponse(false, deviceId); + } + } } diff --git a/lib/features/remote_control/domain/repositories/remote_control_repository.dart b/lib/features/remote_control/domain/repositories/remote_control_repository.dart index 5717f6bd..6d3fdfc9 100644 --- a/lib/features/remote_control/domain/repositories/remote_control_repository.dart +++ b/lib/features/remote_control/domain/repositories/remote_control_repository.dart @@ -17,4 +17,6 @@ abstract class RemoteControlRepository { /// 新增:请求控制权限 (发送 0x04 指令) Future requestControlPermission(String deviceName, String deviceId); + /// 新增:响应控制权限 同意和拒绝(发送 0x05 指令) + void respondPermission(bool bool, String deviceId); } diff --git a/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart b/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart index 293be918..e332648b 100644 --- a/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart +++ b/lib/features/remote_control/presentation/bloc/remote_control_cubit.dart @@ -26,6 +26,7 @@ class RemoteControlCubit extends Cubit { ), ) { _initPacketListener(); + } // 1. 初始化回包监听 (如 0x12 权限) @@ -56,16 +57,52 @@ class RemoteControlCubit extends Cubit { print('>>> [RemoteControl] 去除 CRC 后的 JSON: $jsonString'); final jsonMap = jsonDecode(jsonString); - final respond = jsonMap['request'] ?? ''; - print('>>> [RemoteControl] ✅ 响应结果:$respond'); - // 🔥 当 Web 端推送 switch_control 权限时,更新状态触发弹窗 - if (respond == 'switch_control') { - print('>>> [RemoteControl] ✅ 获得控制权 (respond=switch_control),准备打开弹窗'); - emit(state.copyWith(hasPermission: true, showPermissionRequestDialog: true)); - } else if (respond == 'have_logged_in') { - // 如果是异地登录,也显示弹窗提示 - print('>>> [RemoteControl] ⚠️ 检测到异地登录'); - emit(state.copyWith(showPermissionRequestDialog: true)); + + // 🔥 区分两种数据格式 + final requestType = jsonMap['request']; + final platform = jsonMap['platform']; + final respondData = jsonMap['respond']; + + print('>>> [RemoteControl] 📋 requestType=$requestType, platform=$platform'); + + // 情况 1: 响应格式 - {"respond":{"switchResult":true,"deviceId":"...","holder":"you"}} + if (respondData != null && respondData is Map) { + final switchResult = respondData['switchResult']; + print('>>> [RemoteControl] 📊 收到切换结果响应:switchResult = $switchResult'); + + if (!isClosed) { + if (switchResult == true) { + // 切换成功,当前 APP 失去控制权 + emit(state.copyWith(hasPermission: true, showPermissionRequestDialog: false)); + print('>>> [RemoteControl] ✅ 权限已切'); + } else { + // 切换失败或拒绝,保持当前状态 + emit(state.copyWith(showPermissionRequestDialog: false)); + print('>>> [RemoteControl] ❌ 权限切换失败/被拒绝'); + } + } + } + // 情况 2: 请求格式 - {"request":"switch_control","deviceId":"...","platform":"web",...} + else if (requestType == 'switch_control') { + // 🔥 关键判断:只有当是其他平台(web)请求时才弹窗 + if (platform != null && platform.toString().toLowerCase() != 'app') { + print('>>> [RemoteControl] 🚨 $platform 端请求控制权,打开弹窗询问用户'); + if (!isClosed) { + emit(state.copyWith(showPermissionRequestDialog: true)); + } + } else { + print('>>> [RemoteControl] ℹ️ APP 自己的请求回显,忽略不弹窗'); + } + } + // 情况 3: 异地登录通知 - {"request":"have_logged_in",...} + else if (requestType == 'have_logged_in') { + print('>>> [RemoteControl] ⚠️ 检测到异地登录,打开弹窗提示'); + if (!isClosed) { + emit(state.copyWith(showPermissionRequestDialog: true)); + } + } + else { + print('>>> [RemoteControl] ℹ️ 未知类型的 0x12 包,忽略'); } } catch (e) { print('>>> [RemoteControl] ❌ 解析失败:$e'); @@ -75,6 +112,7 @@ class RemoteControlCubit extends Cubit { print('>>> [RemoteControl] ✅ 0x12 监听器已建立完成'); } + // 2. 开启 100ms 控制循环 (在进入遥控页面或点击“开始”时调用) void startControlLoop() { _timer?.cancel(); @@ -153,7 +191,24 @@ class RemoteControlCubit extends Cubit { void updateEmergency(bool bool) {} - void respondPermission(bool bool) {} + void respondPermission(bool bool, String deviceId) { + emit(state.copyWith(showPermissionRequestDialog: false)); + + // 2. 发送响应到服务端 + _repository.respondPermission(bool, deviceId); + + // 3. 根据用户选择更新控制状态 + if (bool) { + // 用户同意 → APP 失去控制权,Web 端获得控制权 + emit(state.copyWith(hasPermission: false)); + //路由到首页home + + } else { + // 用户拒绝 → APP 继续保持控制权 + emit(state.copyWith(hasPermission: true)); + } + + } void requestControlPermissionS(String deviceName, String deviceId) async { // 1. 关闭弹窗 @@ -193,5 +248,7 @@ class RemoteControlCubit extends Cubit { + + } diff --git a/lib/features/remote_control/presentation/pages/remote_control_page.dart b/lib/features/remote_control/presentation/pages/remote_control_page.dart index 69d52c8a..3b0c0601 100644 --- a/lib/features/remote_control/presentation/pages/remote_control_page.dart +++ b/lib/features/remote_control/presentation/pages/remote_control_page.dart @@ -5,6 +5,7 @@ import 'package:go_router/go_router.dart'; import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; import '../../../../core/app/app_user_cubit.dart'; +import '../../../../core/router/route_paths.dart'; import '../../../devices/presentation/bloc/devices_cubit.dart'; import '../bloc/remote_control_cubit.dart'; import '../bloc/remote_control_state.dart'; @@ -51,11 +52,12 @@ class _RemoteControlPageState extends State { final deviceState = context.watch().state; final currentDevice = deviceState.selectedDevice; - context.read().requestControlPermissionS(currentDevice!.deviceName, "app"); + ///context.read().requestControlPermissionS(currentDevice!.deviceName, "app"); if (currentDevice == null) { return _buildOfflineScaffold(); } + context.read().requestControlPermissionS(currentDevice!.deviceName, "app"); return Scaffold( backgroundColor: Colors.black, @@ -185,14 +187,27 @@ class _RemoteControlPageState extends State { } Widget _buildPermissionDialog(BuildContext context, RemoteControlState state) { + final deviceId = context.read().state.selectedDevice?.deviceName ?? ""; return Container( color: Colors.black54, child: AlertDialog( title: const Text("权限变更"), - content: Text("${state.permissionPlatform}端正请求控制权,同意释放吗?"), + // content: Text("${state.permissionPlatform}端正请求控制权,同意释放吗?"), + content: Text("web端正请求控制权,同意释放吗?"), actions: [ - TextButton(onPressed: () => context.read().respondPermission(false), child: const Text("拒绝")), - TextButton(onPressed: () => context.read().respondPermission(true), child: const Text("同意")), + TextButton(onPressed: () => context.read().respondPermission(false,deviceId), child: const Text("拒绝")), + TextButton( + onPressed: () { + context.read().respondPermission(true, deviceId); + // 🔥 用户同意,延迟跳转到首页 + // Future.delayed(const Duration(milliseconds: 1000), () { + // if (context.mounted) { + // context.go(RoutePaths.home); + // } + // }); + }, + child: const Text("同意"), + ), ], ), );