import 'dart:async'; 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/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 协议发送控制指令和权限请求 class RemoteTcpDatasource { final TcpClient _tcpClient; final UserStorage _userStorage; final ILoggerService _logger = GetIt.I(); RemoteTcpDatasource(this._tcpClient, this._userStorage); /// Sends the existing 0x12 request, with no protocol changes. Future sendSwitchControlRequest( String deviceName, { bool Function()? isCurrent, }) async { ControlPermissionDiagnostics.event('TCP申请检查', { 'device': deviceName, 'tcpConnected': _tcpClient.isConnected, }); if (!_tcpClient.isConnected) { 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 { await _tcpClient .sendPermissionPacket(packet) .timeout(const Duration(seconds: 5)); ControlPermissionDiagnostics.event('TCP申请本地完成', { 'serverReceiptConfirmed': false, 'note': '仅本地写入和flush完成,等待授权回包', }); _logger.logWithLevel( '[ControlPermission] local socket write completed device=' + deviceName + ' cmd=0x12 bytes=' + packet.length.toString() + '; server/Web receipt unconfirmed', shouldLog: true, ); } catch (e) { 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'); } } /// 监听 TCP 回包流 /// 用于接收权限响应、状态更新等 Stream get responseStream => _tcpClient.packetStream; /// 检查 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 agreed, String deviceId) { debugPrint('📤 [进入了TCP层==== 被调用 - agreed=$agreed, deviceId=$deviceId'); // 🔥 添加详细的连接状态日志 debugPrint( '📤 [进入了TCP层==== 当前 TCP 连接状态: isConnected=${_tcpClient.isConnected}', ); if (!_tcpClient.isConnected) { debugPrint('❌ [TCP DataSource] 无法发送权限响应: Socket 未连接'); debugPrint('❌ [TCP DataSource] isConnected=${_tcpClient.isConnected}'); throw Exception('sendSwitchControlResponse TCP 未连接'); } try { debugPrint('📡 [TCP DataSource] TCP 连接正常,准备发送数据...'); // 构造响应 JSON(参考 Android 代码) final response = agreed ? { 'respond': { 'switchResult': true, 'deviceId': deviceId, 'holder': 'you', }, } : { 'respond': { 'switchResult': false, 'deviceId': deviceId, 'reason': 'holder_denied', }, }; debugPrint( '📝 [TCP DataSource] ${agreed ? "同意" : "拒绝"}授权: deviceId=$deviceId', ); final jsonStr = jsonEncode(response); final jsonBytes = utf8.encode(jsonStr); debugPrint('📦 [TCP DataSource] JSON 数据: $jsonStr'); debugPrint('📦 [TCP DataSource] JSON 字节长度: ${jsonBytes.length} 字节'); // 构造完整的协议包 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; } } }