diff --git a/lib/features/connection/data/protobuf_codec.dart b/lib/features/connection/data/protobuf_codec.dart index fd10902..1935ca4 100644 --- a/lib/features/connection/data/protobuf_codec.dart +++ b/lib/features/connection/data/protobuf_codec.dart @@ -138,7 +138,9 @@ class ControlMessageEncoder { } } -/// 被控端上报的远程视频信息(REPORT_RESOLUTION / REPORT_STREAM_MODE)。 +enum TouchMode { legacy, discrete, motion } + +/// 被控端上报的视频信息和触摸能力。 class ReportInfo { final int action; final int width; @@ -146,6 +148,7 @@ class ReportInfo { final int fps; final int streamMode; final List supportedFps; + final TouchMode touchMode; const ReportInfo({ this.action = 0, @@ -154,13 +157,14 @@ class ReportInfo { this.fps = 0, this.streamMode = 0, this.supportedFps = const [], + this.touchMode = TouchMode.legacy, }); } /// protobuf wire format 解码器。 /// /// 与控制端 `com.ttstd.control.ControlMessage`(protobuf 3)字段号完全对齐, -/// 仅解析被控端会回传的字段(action/width/height/fps/stream_mode/supported_fps)。 +/// 解析被控端上报的视频和触摸能力字段。 class ControlMessageDecoder { /// 解析被控端上报的 REPORT_* 消息;无法解析返回 null。 static ReportInfo? decode(Uint8List data) { @@ -169,6 +173,7 @@ class ControlMessageDecoder { int height = 0; int fps = 0; int streamMode = 0; + var touchMode = TouchMode.legacy; final supportedFps = []; final reader = ByteData.sublistView(data); @@ -203,8 +208,30 @@ class ControlMessageDecoder { case 16: supportedFps.add(val); break; + case 17: + touchMode = switch (val) { + 1 => TouchMode.discrete, + 2 => TouchMode.motion, + _ => TouchMode.legacy, + }; + break; } break; + case 2: + final length = _readVarint(reader, pos); + pos = length.$2; + final end = pos + length.$1; + if (end < pos || end > data.length) return null; + if (field == 16) { + while (pos < end) { + final fps = _readVarint(reader, pos); + pos = fps.$2; + if (pos > end) return null; + supportedFps.add(fps.$1); + } + } + pos = end; + break; default: // 未知 wire type:跳过(解析到 known fields 前不应出现) return null; @@ -220,6 +247,7 @@ class ControlMessageDecoder { fps: fps, streamMode: streamMode, supportedFps: supportedFps, + touchMode: touchMode, ); } diff --git a/lib/features/connection/data/signaling_client.dart b/lib/features/connection/data/signaling_client.dart index ed79b02..7d812d8 100644 --- a/lib/features/connection/data/signaling_client.dart +++ b/lib/features/connection/data/signaling_client.dart @@ -16,6 +16,7 @@ import '../domain/connection_models.dart'; class SignalingClient { WebSocketChannel? _channel; StreamSubscription? _subscription; + Map? turnConfig; /// 是否已连接(可复用,供上层判断)。 bool get isConnected => _channel != null; @@ -35,7 +36,8 @@ class SignalingClient { Future connect(String serverUrl, {String? targetSn}) async { final sessionVersion = TokenStorage.sessionVersion; - final uri = Uri.parse('$serverUrl?sn=$targetSn'); + final uri = Uri.parse(serverUrl).replace(queryParameters: {'sn': targetSn}); + if (uri.scheme != 'wss') throw StateError('远程协助需要安全信令连接'); await LocalNetworkAccess.ensure(uri); if (sessionVersion != TokenStorage.sessionVersion) return; final token = TokenStorage.accessToken ?? ''; @@ -45,21 +47,24 @@ class SignalingClient { pingInterval: const Duration(seconds: 20), ); + final registered = Completer(); _subscription = _channel!.stream.listen( - (data) => _handleRaw(data), + (data) => _handleRaw(data, registered), onError: (Object e) { debugPrint('[webrtc] 信令连接错误'); + if (!registered.isCompleted) registered.completeError(StateError('信令连接异常')); onError?.call('信令连接异常'); }, onDone: () { debugPrint('[webrtc] 信令连接关闭(serverUrl=$serverUrl)'); + if (!registered.isCompleted) registered.completeError(StateError('信令连接已关闭')); onConnectionChanged?.call(false); }, ); - debugPrint('[webrtc] 信令已发起连接'); + await registered.future.timeout(const Duration(seconds: 10)); } - void _handleRaw(dynamic data) { + void _handleRaw(dynamic data, Completer registered) { if (data is String) { try { final json = jsonDecode(data) as Map; @@ -67,6 +72,11 @@ class SignalingClient { debugPrint( '[webrtc] 信令收到: type=${msg.type}, from=${msg.fromDeviceId}, to=${msg.toDeviceId}', ); + if (msg.type == SignalType.registerSuccess && !registered.isCompleted) { + final config = jsonDecode(msg.payload ?? '{}') as Map; + turnConfig = config.containsKey('urls') ? config : null; + registered.complete(); + } onMessage?.call(msg); } catch (e) { debugPrint('[webrtc] 信令解析失败: $e'); @@ -88,5 +98,6 @@ class SignalingClient { _channel?.sink.close(); } catch (_) {} _channel = null; + turnConfig = null; } } diff --git a/lib/features/connection/data/webrtc_orchestrator.dart b/lib/features/connection/data/webrtc_orchestrator.dart index 46996ff..e833c07 100644 --- a/lib/features/connection/data/webrtc_orchestrator.dart +++ b/lib/features/connection/data/webrtc_orchestrator.dart @@ -15,47 +15,23 @@ import '../domain/connection_models.dart'; /// - 与信令客户端配合完成 OFFER/ANSWER/ICE 握手。 class WebRtcOrchestrator { static const _dataChannelLabel = 'control_channel'; - // ICE 服务器(与 webrtc_controller_flutter 的 ice_servers.dart 完全一致)。 - static const _iceServers = [ - {'urls': 'stun:stun.l.google.com:19302'}, - {'urls': 'stun:175.178.213.60:3478'}, - { - 'urls': [ - 'turns:175.178.213.60:5349', - 'turn:175.178.213.60:3478?transport=tcp', - 'turn:175.178.213.60:3478', - ], - 'username': 'fanhuitong', - 'credential': 'Fan19961907..', - }, - {'urls': 'stun:47.242.112.133:3478'}, - { - 'urls': 'turn:47.242.112.133:3478', - 'username': 'ttstd', - 'credential': 'fanhuitong', - }, - { - 'urls': [ - 'stun:192.168.5.224:3478', - 'turn:192.168.5.224:3478', - ], - 'username': 'tt', - 'credential': 'fht', - }, - ]; - final SignalingClient _signaling; final String _targetSn; final String _clientName; RTCPeerConnection? _pc; RTCDataChannel? _controlChannel; + String? _sessionId; + bool _remoteDescriptionSet = false; + final _localCandidates = []; + final _remoteCandidates = []; /// 远程屏幕渲染器(供页面 RTCVideoView 使用)。 final RTCVideoRenderer remoteRenderer = RTCVideoRenderer(); /// 被控端上报的 REPORT_* 消息(REPORT_RESOLUTION / REPORT_STREAM_MODE)。 void Function(ReportInfo report)? onReport; + TouchMode touchMode = TouchMode.legacy; /// 连接状态变化(用于 UI 显示 "已连接")。 void Function(bool connected)? onConnectionState; @@ -86,6 +62,7 @@ class WebRtcOrchestrator { if (message.isBinary) { final report = ControlMessageDecoder.decode(message.binary); if (report != null) { + if (report.touchMode != TouchMode.legacy) touchMode = report.touchMode; onReport?.call(report); } } @@ -117,8 +94,12 @@ class WebRtcOrchestrator { } Future _initPeerConnection() async { + final turn = _signaling.turnConfig; final config = { - 'iceServers': _iceServers, + 'iceServers': [ + {'urls': 'stun:stun.l.google.com:19302'}, + ?turn, + ], 'sdpSemantics': 'unified-plan', }; _pc = await createPeerConnection(config); @@ -152,44 +133,66 @@ class WebRtcOrchestrator { }; _pc!.onIceCandidate = (RTCIceCandidate candidate) { - _signaling.send(SignalMessage( - type: SignalType.iceCandidate, - fromDeviceId: _clientName, - toDeviceId: _targetSn, - deviceType: 'CONTROLLER', - payload: jsonEncode({ - 'sdpMid': candidate.sdpMid, - 'sdpMLineIndex': candidate.sdpMLineIndex, - 'candidate': candidate.candidate, - }), - )); + if (candidate.candidate == null) return; + if (_sessionId == null) { + if (_localCandidates.length < 128) _localCandidates.add(candidate); + } else { + _sendCandidate(candidate); + } }; } - /// 处理信令消息:ANSWER / ICE_CANDIDATE。 + void _sendCandidate(RTCIceCandidate candidate) { + _signaling.send(SignalMessage( + type: SignalType.iceCandidate, + toDeviceId: _targetSn, + sessionId: _sessionId, + payload: jsonEncode({ + 'sdpMid': candidate.sdpMid, + 'sdpMLineIndex': candidate.sdpMLineIndex, + 'candidate': candidate.candidate, + }), + )); + } + Future handleSignal(SignalMessage message) async { - if (_pc == null) { - debugPrint('[webrtc] handleSignal skipped: pc not ready, type=${message.type}'); + final peer = _pc; + if (peer == null || + message.fromDeviceId != _targetSn || + message.deviceType != 'CONTROLLED' || + message.sessionId == null) { return; } - switch (message.type) { - case SignalType.answer: - final payload = jsonDecode(message.payload ?? '{}') as Map; - final sdp = payload['sdp'] as String?; - if (sdp != null) { - debugPrint('[webrtc] 收到 ANSWER,setRemoteDescription'); - await _pc!.setRemoteDescription(RTCSessionDescription(sdp, 'answer')); - } - break; - case SignalType.iceCandidate: - final payload = jsonDecode(message.payload ?? '{}') as Map; - final candidate = RTCIceCandidate( - payload['candidate'] as String? ?? '', - payload['sdpMid'] as String? ?? '', - (payload['sdpMLineIndex'] as num?)?.toInt() ?? 0, - ); - await _pc!.addCandidate(candidate); - break; + if (_sessionId != null && _sessionId != message.sessionId) return; + if (message.type == SignalType.iceCandidate && !_remoteDescriptionSet) { + if (_remoteCandidates.length < 128) _remoteCandidates.add(message); + return; + } + if (message.type == SignalType.answer && _sessionId != null) return; + if (message.type != SignalType.answer && message.type != SignalType.iceCandidate) return; + final payload = jsonDecode(message.payload ?? '{}') as Map; + if (message.type == SignalType.answer) { + final sdp = payload['sdp'] as String?; + if (sdp == null) return; + _sessionId = message.sessionId; + await peer.setRemoteDescription(RTCSessionDescription(sdp, 'answer')); + if (_pc != peer) return; + _remoteDescriptionSet = true; + for (final candidate in _localCandidates) { + _sendCandidate(candidate); + } + _localCandidates.clear(); + final queued = List.of(_remoteCandidates); + _remoteCandidates.clear(); + for (final candidate in queued) { + await handleSignal(candidate); + } + } else { + await peer.addCandidate(RTCIceCandidate( + payload['candidate'] as String?, + payload['sdpMid'] as String?, + (payload['sdpMLineIndex'] as num?)?.toInt(), + )); } } diff --git a/lib/features/connection/domain/connection_models.dart b/lib/features/connection/domain/connection_models.dart index f979e4a..0c08f07 100644 --- a/lib/features/connection/domain/connection_models.dart +++ b/lib/features/connection/domain/connection_models.dart @@ -19,6 +19,7 @@ class SignalType { static const targetOffline = 'TARGET_OFFLINE'; static const requestTimeout = 'REQUEST_TIMEOUT'; static const forceLogout = 'FORCE_LOGOUT'; + static const sessionEnded = 'SESSION_ENDED'; static const ping = 'PING'; } @@ -30,6 +31,7 @@ class SignalMessage { final String? toDeviceId; final String? deviceType; final String? payload; + final String? sessionId; const SignalMessage({ required this.type, @@ -37,6 +39,7 @@ class SignalMessage { this.toDeviceId, this.deviceType, this.payload, + this.sessionId, }); factory SignalMessage.fromJson(Map json) { @@ -46,6 +49,7 @@ class SignalMessage { toDeviceId: json['toDeviceId'] as String?, deviceType: json['deviceType'] as String?, payload: json['payload'] as String?, + sessionId: json['sessionId'] as String?, ); } @@ -55,6 +59,7 @@ class SignalMessage { if (fromDeviceId != null) 'fromDeviceId': fromDeviceId, if (toDeviceId != null) 'toDeviceId': toDeviceId, if (deviceType != null) 'deviceType': deviceType, + if (sessionId != null) 'sessionId': sessionId, if (payload != null) 'payload': payload, }; } diff --git a/lib/features/connection/presentation/connection_controller.dart b/lib/features/connection/presentation/connection_controller.dart index 07cabb9..8adbe1a 100644 --- a/lib/features/connection/presentation/connection_controller.dart +++ b/lib/features/connection/presentation/connection_controller.dart @@ -103,6 +103,7 @@ class ConnectionController extends Notifier { _disposed = true; signaling.onMessage = null; signaling.onError = null; + signaling.onConnectionChanged = null; signaling.dispose(); final orchestrator = _orchestrator; _orchestrator = null; @@ -155,24 +156,30 @@ class ConnectionController extends Notifier { _onReport(report); }; + void endSession(String reason) { + if (_disposed) return; + unawaited(disconnect(errorMessage: reason)); + } + signaling.onMessage = (message) { - // 先透传给 WebRTC 编排器处理(ANSWER/ICE 等),确保握手能继续 - _orchestrator?.handleSignal(message); - // 仅"明确被拒"才进入错误态;TARGET_OFFLINE 可能因握手时序/目标会话短暂未就绪 - // 而误报(如设备端刚连上信令、正在应答),不立即判定失败,避免闪断"设备不在线"。 - if (message.type == SignalType.connectionRejected) { - state = ConnectionSessionState( - state: ConnectionState.error, - errorMessage: '连接被拒绝', - ); + switch (message.type) { + case SignalType.connectionRejected: + endSession('连接被拒绝'); + case SignalType.targetOffline: + endSession('设备信令未上线,请确认远程协助已开启'); + case SignalType.sessionEnded: + if (message.fromDeviceId == 'server') endSession('远程协助已结束'); + default: + final handling = _orchestrator?.handleSignal(message); + if (handling != null) { + unawaited(handling.catchError((Object error) => endSession('信令协商失败'))); + } } }; - signaling.onError = (error) { - state = ConnectionSessionState( - state: ConnectionState.error, - errorMessage: error, - ); + signaling.onConnectionChanged = (connected) { + if (!connected) endSession('信令连接已关闭'); }; + signaling.onError = endSession; try { await signaling.connect(signalServerUrl, targetSn: sn); @@ -180,10 +187,7 @@ class ConnectionController extends Notifier { await _orchestrator?.start(); } catch (e) { if (_disposed) return; - state = ConnectionSessionState( - state: ConnectionState.error, - errorMessage: '连接失败: $e', - ); + endSession('连接失败: $e'); } } @@ -213,6 +217,8 @@ class ConnectionController extends Notifier { } } + TouchMode get touchMode => _orchestrator?.touchMode ?? TouchMode.legacy; + /// 发送点击(相对坐标 0~1)。 void sendTap(double relX, double relY) { debugPrint( @@ -235,7 +241,7 @@ class ConnectionController extends Notifier { _orchestrator?.sendSwipe(relX1, relY1, relX2, relY2); } - /// 发送实时触摸事件(MOTION_EVENT,跟手用)。action:0=DOWN,1=UP,2=MOVE。 + /// 发送实时触摸事件。action 取值为 0=DOWN、1=UP、2=MOVE、3=CANCEL。 void sendMotionEvent(int action, double relX, double relY) { debugPrint( '[touch] MOTION action=$action rel=(${relX.toStringAsFixed(3)}, ${relY.toStringAsFixed(3)})', @@ -311,12 +317,13 @@ class ConnectionController extends Notifier { } /// 关闭并清理。 - Future disconnect() async { + Future disconnect({String? errorMessage}) async { final signaling = ref.read(signalingClientProvider); final orchestrator = _orchestrator; _orchestrator = null; signaling.onMessage = null; signaling.onError = null; + signaling.onConnectionChanged = null; signaling.dispose(); if (orchestrator != null) { orchestrator.onConnectionState = null; @@ -325,7 +332,10 @@ class ConnectionController extends Notifier { await _videoRecorder.dispose(); await orchestrator?.dispose(); if (!_disposed) { - state = const ConnectionSessionState(state: ConnectionState.ended); + state = ConnectionSessionState( + state: errorMessage == null ? ConnectionState.ended : ConnectionState.error, + errorMessage: errorMessage, + ); } } } diff --git a/lib/features/connection/presentation/remote_control_page.dart b/lib/features/connection/presentation/remote_control_page.dart index a6d9e28..0004201 100644 --- a/lib/features/connection/presentation/remote_control_page.dart +++ b/lib/features/connection/presentation/remote_control_page.dart @@ -9,6 +9,7 @@ import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; import '../../../core/platform/platform_capabilities.dart'; import '../../device/presentation/device_switcher.dart'; import '../data/connection_providers.dart'; +import '../data/protobuf_codec.dart'; import '../domain/connection_models.dart' as connection; import 'connection_controller.dart'; @@ -160,10 +161,10 @@ class _RemoteControlPageState extends ConsumerState { final vh = constraints.maxHeight; return Listener( behavior: HitTestBehavior.opaque, - onPointerDown: (e) => _onPointerDown(e.localPosition, vw, vh), - onPointerMove: (e) => _onPointerMove(e.localPosition, vw, vh), - onPointerUp: (e) => _onPointerUp(e.localPosition, vw, vh), - onPointerCancel: (e) => _onPointerCancel(), + onPointerDown: (e) => _onPointerDown(e, vw, vh), + onPointerMove: (e) => _onPointerMove(e, vw, vh), + onPointerUp: (e) => _onPointerUp(e, vw, vh), + onPointerCancel: (e) => _onPointerCancel(e, vw, vh), child: Container( color: Colors.black, alignment: Alignment.center, @@ -181,6 +182,8 @@ class _RemoteControlPageState extends ConsumerState { /// 触摸起点(本地坐标)与按下时间。 Offset? _downPos; + int? _activePointer; + TouchMode _gestureMode = TouchMode.legacy; DateTime? _downTime; /// 长按超时(400ms 后视为长按)。 static const _longPressTimeout = Duration(milliseconds: 400); @@ -194,17 +197,25 @@ class _RemoteControlPageState extends ConsumerState { double _rx(double x, double w) => w <= 0 ? 0 : (x / w).clamp(0.0, 1.0); double _ry(double y, double h) => h <= 0 ? 0 : (y / h).clamp(0.0, 1.0); - void _onPointerDown(Offset local, double vw, double vh) { + void _onPointerDown(PointerDownEvent event, double vw, double vh) { + if (_activePointer != null || vw <= 0 || vh <= 0) return; + final local = event.localPosition; + final controller = ref.read(connectionControllerProvider.notifier); + _activePointer = event.pointer; + _gestureMode = controller.touchMode; _downPos = local; _downTime = DateTime.now(); _lastMoveSample = null; - ref.read(connectionControllerProvider.notifier) - .sendMotionEvent(0, _rx(local.dx, vw), _ry(local.dy, vh)); // ACTION_DOWN + if (_gestureMode != TouchMode.discrete) { + controller.sendMotionEvent(0, _rx(local.dx, vw), _ry(local.dy, vh)); + } } - void _onPointerMove(Offset local, double vw, double vh) { - final down = _downPos; - if (down == null) return; + void _onPointerMove(PointerMoveEvent event, double vw, double vh) { + if (_activePointer != event.pointer || _gestureMode == TouchMode.discrete) { + return; + } + final local = event.localPosition; // 节流采样,减少指令洪泛 final now = DateTime.now(); final last = _lastMoveSample; @@ -214,22 +225,24 @@ class _RemoteControlPageState extends ConsumerState { .sendMotionEvent(2, _rx(local.dx, vw), _ry(local.dy, vh)); // ACTION_MOVE } - void _onPointerUp(Offset local, double vw, double vh) { + void _onPointerUp(PointerUpEvent event, double vw, double vh) { + if (_activePointer != event.pointer) return; + final local = event.localPosition; final down = _downPos; final downTime = _downTime; - _downPos = null; - _downTime = null; - _lastMoveSample = null; - if (down == null || vw <= 0 || vh <= 0) return; + _resetGesture(); final controller = ref.read(connectionControllerProvider.notifier); + if (_gestureMode != TouchMode.discrete) { + controller.sendMotionEvent(1, _rx(local.dx, vw), _ry(local.dy, vh)); + } + if (_gestureMode == TouchMode.motion || down == null || vw <= 0 || vh <= 0) { + return; + } final duration = DateTime.now().difference(downTime ?? DateTime.now()); final dx = (_rx(local.dx, vw) - _rx(down.dx, vw)).abs(); final dy = (_ry(local.dy, vh) - _ry(down.dy, vh)).abs(); - // 先补发 ACTION_UP,结束触摸 - controller.sendMotionEvent(1, _rx(local.dx, vw), _ry(local.dy, vh)); - // 位移很小且时间短 → 点击;否则 → 滑动;长按由按下时长判定 if (duration >= _longPressTimeout && dx < _tapSlop && dy < _tapSlop) { controller.sendLongPress(_rx(down.dx, vw), _ry(down.dy, vh)); @@ -245,7 +258,18 @@ class _RemoteControlPageState extends ConsumerState { } } - void _onPointerCancel() { + void _onPointerCancel(PointerCancelEvent event, double vw, double vh) { + if (_activePointer != event.pointer) return; + if (_gestureMode != TouchMode.discrete) { + final local = event.localPosition; + ref.read(connectionControllerProvider.notifier) + .sendMotionEvent(3, _rx(local.dx, vw), _ry(local.dy, vh)); + } + _resetGesture(); + } + + void _resetGesture() { + _activePointer = null; _downPos = null; _downTime = null; _lastMoveSample = null;