feat(connection): 添加远程控制路由并更新版本策略
- 新增 /connection 路由,从全局选中设备 SN 读取并渲染远程控制页 - 首页镜像操作改为静默下发 mirror 命令并跳转远程控制页 - 更新 AGENTS.md 版本管理策略为使用最新稳定版本 - 调整 pubspec.lock 中 hooks 与 record_use 版本
This commit is contained in:
1 parent
26190c1005
commit
41a514e9cc
11 files changed
+1087
-12
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../app/constants/app_constants.dart';
|
||||
import '../../../core/storage/token_storage.dart';
|
||||
import '../presentation/connection_controller.dart';
|
||||
import 'signaling_client.dart';
|
||||
|
||||
/// 信令 WebSocket 地址(从 baseUrl 推导)。
|
||||
///
|
||||
/// baseUrl 形如 http://host:port/api/,信令端点固定为 /ws/signal(后端新增)。
|
||||
String get signalServerUrl {
|
||||
final base = AppConstants.kBaseUrl; // e.g. http://192.168.100.244:8000/api/
|
||||
try {
|
||||
final uri = Uri.parse(base);
|
||||
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';
|
||||
return '$scheme://${uri.authority}/ws/signal';
|
||||
} catch (_) {
|
||||
return 'ws://localhost:8000/ws/signal';
|
||||
}
|
||||
}
|
||||
|
||||
/// 信令客户端(会话级单例)。
|
||||
final signalingClientProvider = Provider<SignalingClient>((ref) {
|
||||
final client = SignalingClient();
|
||||
ref.onDispose(client.dispose);
|
||||
return client;
|
||||
});
|
||||
|
||||
/// client 端标识(用于信令 fromDeviceId)。
|
||||
///
|
||||
/// 实际身份由后端从 JWT 解析,这里仅作客户端本地标识,取设备 ID 或固定值均可。
|
||||
final clientNameProvider = Provider<String>((ref) {
|
||||
final deviceId = TokenStorage.deviceId;
|
||||
return deviceId.isNotEmpty ? deviceId : 'client';
|
||||
});
|
||||
|
||||
/// 远程控制控制器(按目标设备 SN 隔离,管理连接状态机)。
|
||||
final connectionControllerProvider =
|
||||
NotifierProvider<ConnectionController, ConnectionSessionState>(
|
||||
ConnectionController.new,
|
||||
);
|
||||
@@ -0,0 +1,139 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// 控制指令 Action 枚举(与控制端 proto 的 Action 字段号一致)。
|
||||
class ActionType {
|
||||
static const unknown = 0;
|
||||
static const touch = 1;
|
||||
static const swipe = 2;
|
||||
static const key = 3;
|
||||
static const longPress = 4;
|
||||
static const motionEvent = 5;
|
||||
static const setResolution = 6;
|
||||
static const reportResolution = 7;
|
||||
static const setStreamMode = 8;
|
||||
static const reportStreamMode = 9;
|
||||
}
|
||||
|
||||
/// protobuf wire format 编码器。
|
||||
///
|
||||
/// 与控制端 `com.ttstd.control.ControlMessage`(protobuf 3)字段号完全对齐:
|
||||
/// action=1, x=2, y=3, x1=4, y1=5, x2=6, y2=7, duration=8,
|
||||
/// key_code=9, key_action=10, motion_action=11, width=12, height=13,
|
||||
/// fps=14, stream_mode=15, supported_fps=16(repeated int32)。
|
||||
///
|
||||
/// 坐标均为相对屏幕百分比(0.0~1.0),被控端乘以真实分辨率还原像素。
|
||||
class ControlMessageEncoder {
|
||||
final int action;
|
||||
|
||||
// 单点坐标
|
||||
final double x;
|
||||
final double y;
|
||||
|
||||
// 滑动起止
|
||||
final double x1;
|
||||
final double y1;
|
||||
final double x2;
|
||||
final double y2;
|
||||
final int duration;
|
||||
|
||||
// 按键
|
||||
final int keyCode;
|
||||
final int keyAction;
|
||||
|
||||
// 原始动作
|
||||
final int motionAction;
|
||||
|
||||
// 分辨率/帧率
|
||||
final int width;
|
||||
final int height;
|
||||
final int fps;
|
||||
final int streamMode;
|
||||
|
||||
const ControlMessageEncoder({
|
||||
required this.action,
|
||||
this.x = 0,
|
||||
this.y = 0,
|
||||
this.x1 = 0,
|
||||
this.y1 = 0,
|
||||
this.x2 = 0,
|
||||
this.y2 = 0,
|
||||
this.duration = 0,
|
||||
this.keyCode = 0,
|
||||
this.keyAction = 0,
|
||||
this.motionAction = 0,
|
||||
this.width = 0,
|
||||
this.height = 0,
|
||||
this.fps = 0,
|
||||
this.streamMode = 0,
|
||||
});
|
||||
|
||||
/// 编码为 protobuf 二进制字节数组。
|
||||
Uint8List encode() {
|
||||
final out = BytesBuilder(copy: false);
|
||||
|
||||
// 1: action (enum=int32)
|
||||
_writeVarintField(out, 1, action);
|
||||
|
||||
// 2: x, 3: y (double, wire type 1)
|
||||
if (x != 0) _writeFixed64Field(out, 2, x);
|
||||
if (y != 0) _writeFixed64Field(out, 3, y);
|
||||
|
||||
// 4-7: swipe 起止
|
||||
if (x1 != 0) _writeFixed64Field(out, 4, x1);
|
||||
if (y1 != 0) _writeFixed64Field(out, 5, y1);
|
||||
if (x2 != 0) _writeFixed64Field(out, 6, x2);
|
||||
if (y2 != 0) _writeFixed64Field(out, 7, y2);
|
||||
|
||||
// 8: duration (int64)
|
||||
if (duration != 0) _writeVarintField(out, 8, duration);
|
||||
|
||||
// 9: key_code, 10: key_action (int32)
|
||||
if (keyCode != 0) _writeVarintField(out, 9, keyCode);
|
||||
if (keyAction != 0) _writeVarintField(out, 10, keyAction);
|
||||
|
||||
// 11: motion_action
|
||||
if (motionAction != 0) _writeVarintField(out, 11, motionAction);
|
||||
|
||||
// 12-14: width/height/fps
|
||||
if (width != 0) _writeVarintField(out, 12, width);
|
||||
if (height != 0) _writeVarintField(out, 13, height);
|
||||
if (fps != 0) _writeVarintField(out, 14, fps);
|
||||
|
||||
// 15: stream_mode
|
||||
if (streamMode != 0) _writeVarintField(out, 15, streamMode);
|
||||
|
||||
return out.toBytes();
|
||||
}
|
||||
|
||||
// ---- protobuf wire format 原语 ----
|
||||
|
||||
void _writeVarintField(BytesBuilder out, int field, int value) {
|
||||
_writeTag(out, field, 0); // wire type 0 = varint
|
||||
_writeVarint(out, value);
|
||||
}
|
||||
|
||||
void _writeFixed64Field(BytesBuilder out, int field, double value) {
|
||||
_writeTag(out, field, 1); // wire type 1 = 64-bit (double)
|
||||
// protobuf 的 fixed64/double 必须为 little-endian,否则设备端解析出错误值(如 NaN/Infinity)
|
||||
final bd = ByteData(8);
|
||||
bd.setFloat64(0, value, Endian.little);
|
||||
out.add(bd.buffer.asUint8List());
|
||||
}
|
||||
|
||||
void _writeTag(BytesBuilder out, int field, int wireType) {
|
||||
_writeVarint(out, (field << 3) | wireType);
|
||||
}
|
||||
|
||||
void _writeVarint(BytesBuilder out, int value) {
|
||||
// 转成无符号 64 位表示,配合逻辑右移 >>>,避免负数算术右移导致死循环(OOM)。
|
||||
var v = value.toUnsigned(64);
|
||||
while (true) {
|
||||
if ((v & ~0x7F) == 0) {
|
||||
out.addByte(v & 0xFF);
|
||||
break;
|
||||
}
|
||||
out.addByte((v & 0x7F) | 0x80);
|
||||
v = v >>> 7;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'package:web_socket_channel/io.dart';
|
||||
|
||||
import '../../../core/storage/token_storage.dart';
|
||||
import '../domain/connection_models.dart';
|
||||
|
||||
/// WebRTC 信令 WebSocket 客户端(控制端)。
|
||||
///
|
||||
/// 遵循平台原有用户逻辑:控制端为家属端 client,握手时携带
|
||||
/// `Authorization: Bearer <token>`,由后端信令服务识别 client 身份。
|
||||
class SignalingClient {
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _subscription;
|
||||
|
||||
/// 是否已连接(可复用,供上层判断)。
|
||||
bool get isConnected => _channel != null;
|
||||
|
||||
/// 消息回调:上游处理 OFFER/ANSWER/ICE/REJECTED/OFFLINE 等。
|
||||
void Function(SignalMessage message)? onMessage;
|
||||
|
||||
/// 连接状态回调。
|
||||
void Function(bool connected)? onConnectionChanged;
|
||||
|
||||
void Function(String error)? onError;
|
||||
|
||||
/// 建立信令连接。
|
||||
///
|
||||
/// [serverUrl] WebSocket 地址(如 ws://host:port/ws/signal)。
|
||||
/// [targetSn] 目标设备 SN(作为 query 参数传给服务端做绑定校验)。
|
||||
Future<void> connect(String serverUrl, {String? targetSn}) async {
|
||||
final token = TokenStorage.accessToken ?? '';
|
||||
|
||||
final uri = Uri.parse('$serverUrl?sn=$targetSn');
|
||||
_channel = IOWebSocketChannel.connect(
|
||||
uri,
|
||||
headers: {'Authorization': 'Bearer $token'},
|
||||
pingInterval: const Duration(seconds: 20),
|
||||
);
|
||||
|
||||
_subscription = _channel!.stream.listen(
|
||||
(data) => _handleRaw(data),
|
||||
onError: (Object e) {
|
||||
debugPrint('[webrtc] 信令错误: $e');
|
||||
onError?.call('信令连接异常');
|
||||
},
|
||||
onDone: () {
|
||||
debugPrint('[webrtc] 信令连接关闭(serverUrl=$serverUrl)');
|
||||
onConnectionChanged?.call(false);
|
||||
},
|
||||
);
|
||||
debugPrint('[webrtc] 信令已发起连接: $uri');
|
||||
}
|
||||
|
||||
void _handleRaw(dynamic data) {
|
||||
if (data is String) {
|
||||
try {
|
||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||
final msg = SignalMessage.fromJson(json);
|
||||
debugPrint('[webrtc] 信令收到: type=${msg.type}, from=${msg.fromDeviceId}, to=${msg.toDeviceId}');
|
||||
onMessage?.call(msg);
|
||||
} catch (e) {
|
||||
debugPrint('[webrtc] 信令解析失败: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 发送信令消息。
|
||||
void send(SignalMessage message) {
|
||||
if (_channel == null) return;
|
||||
_channel!.sink.add(jsonEncode(message.toJson()));
|
||||
}
|
||||
|
||||
/// 主动关闭连接。
|
||||
void dispose() {
|
||||
_subscription?.cancel();
|
||||
_subscription = null;
|
||||
try {
|
||||
_channel?.sink.close();
|
||||
} catch (_) {}
|
||||
_channel = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_webrtc/flutter_webrtc.dart';
|
||||
|
||||
import 'protobuf_codec.dart';
|
||||
import 'signaling_client.dart';
|
||||
import '../domain/connection_models.dart';
|
||||
|
||||
/// WebRTC 编排器(控制端 / Offer 方)。
|
||||
///
|
||||
/// - 只收屏幕画面(RECV_ONLY video track)。
|
||||
/// - 创建 `control_channel` DataChannel,用于向被控端发送触摸/按键指令。
|
||||
/// - 与信令客户端配合完成 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;
|
||||
|
||||
/// 远程屏幕渲染器(供页面 RTCVideoView 使用)。
|
||||
final RTCVideoRenderer remoteRenderer = RTCVideoRenderer();
|
||||
|
||||
/// 接收到的被控端报告消息(如 REPORT_RESOLUTION)。
|
||||
void Function(Uint8List data)? onControlMessage;
|
||||
|
||||
/// 连接状态变化(用于 UI 显示 "已连接")。
|
||||
void Function(bool connected)? onConnectionState;
|
||||
|
||||
/// 是否已建立媒体连接。
|
||||
bool get isConnected =>
|
||||
_pc?.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected;
|
||||
|
||||
WebRtcOrchestrator({
|
||||
required SignalingClient signaling,
|
||||
required String targetSn,
|
||||
required String clientName,
|
||||
}) : _signaling = signaling,
|
||||
_targetSn = targetSn,
|
||||
_clientName = clientName; // ignore: prefer_initializing_formals
|
||||
|
||||
/// 发起连接:创建 PeerConnection + DataChannel + 发送 OFFER。
|
||||
Future<void> start() async {
|
||||
await _initPeerConnection();
|
||||
|
||||
// 创建 control_channel(有序、可靠,保证指令不丢)
|
||||
final dataChannelInit = RTCDataChannelInit()
|
||||
..ordered = true
|
||||
..protocol = _dataChannelLabel;
|
||||
_controlChannel = await _pc!.createDataChannel(_dataChannelLabel, dataChannelInit);
|
||||
_controlChannel!.onMessage = (RTCDataChannelMessage message) {
|
||||
if (message.isBinary) {
|
||||
onControlMessage?.call(message.binary);
|
||||
}
|
||||
};
|
||||
_controlChannel!.onDataChannelState = (RTCDataChannelState state) {
|
||||
debugPrint('[webrtc] control_channel state: $state');
|
||||
};
|
||||
|
||||
// 创建 Offer
|
||||
final offer = await _pc!.createOffer();
|
||||
await _pc!.setLocalDescription(offer);
|
||||
|
||||
// 通过信令发送 OFFER(带 username)
|
||||
_signaling.send(SignalMessage(
|
||||
type: SignalType.offer,
|
||||
fromDeviceId: _clientName,
|
||||
toDeviceId: _targetSn,
|
||||
deviceType: 'CONTROLLER',
|
||||
payload: jsonEncode({
|
||||
'sdp': offer.sdp,
|
||||
'username': _clientName,
|
||||
}),
|
||||
));
|
||||
debugPrint('[webrtc] OFFER 已发送 → $_targetSn');
|
||||
}
|
||||
|
||||
Future<void> _initPeerConnection() async {
|
||||
final config = {
|
||||
'iceServers': _iceServers,
|
||||
'sdpSemantics': 'unified-plan',
|
||||
};
|
||||
_pc = await createPeerConnection(config);
|
||||
|
||||
// 只收屏幕:添加一个 RECV_ONLY video transceiver
|
||||
final transceiverInit = RTCRtpTransceiverInit();
|
||||
transceiverInit.direction = TransceiverDirection.RecvOnly;
|
||||
await _pc!.addTransceiver(
|
||||
kind: RTCRtpMediaType.RTCRtpMediaTypeVideo,
|
||||
init: transceiverInit,
|
||||
);
|
||||
|
||||
_pc!.onTrack = (RTCTrackEvent event) {
|
||||
debugPrint('[webrtc] 收到远程屏幕轨道');
|
||||
final stream = event.streams.isNotEmpty ? event.streams.first : null;
|
||||
if (stream != null) {
|
||||
// RTCVideoRenderer 必须先 initialize() 再设置 srcObject,否则抛
|
||||
// "Call initialize before setting the stream" 异常,导致画面不渲染。
|
||||
remoteRenderer.initialize().then((_) {
|
||||
remoteRenderer.srcObject = stream;
|
||||
}).catchError((e) {
|
||||
debugPrint('[webrtc] renderer initialize error: $e');
|
||||
});
|
||||
onConnectionState?.call(true);
|
||||
}
|
||||
};
|
||||
|
||||
_pc!.onConnectionState = (RTCPeerConnectionState state) {
|
||||
debugPrint('[webrtc] connection state: ${state.name}');
|
||||
if (state == RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
|
||||
onConnectionState?.call(true);
|
||||
} else if (state == RTCPeerConnectionState.RTCPeerConnectionStateDisconnected ||
|
||||
state == RTCPeerConnectionState.RTCPeerConnectionStateFailed ||
|
||||
state == RTCPeerConnectionState.RTCPeerConnectionStateClosed) {
|
||||
onConnectionState?.call(false);
|
||||
}
|
||||
};
|
||||
|
||||
_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,
|
||||
}),
|
||||
));
|
||||
};
|
||||
}
|
||||
|
||||
/// 处理信令消息:ANSWER / ICE_CANDIDATE。
|
||||
Future<void> handleSignal(SignalMessage message) async {
|
||||
if (_pc == null) {
|
||||
debugPrint('[webrtc] handleSignal skipped: pc not ready, type=${message.type}');
|
||||
return;
|
||||
}
|
||||
switch (message.type) {
|
||||
case SignalType.answer:
|
||||
final payload = jsonDecode(message.payload ?? '{}') as Map<String, dynamic>;
|
||||
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<String, dynamic>;
|
||||
final candidate = RTCIceCandidate(
|
||||
payload['candidate'] as String? ?? '',
|
||||
payload['sdpMid'] as String? ?? '',
|
||||
(payload['sdpMLineIndex'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
await _pc!.addCandidate(candidate);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// 发送控制指令(protobuf 二进制)。
|
||||
void sendCommand(Uint8List bytes) {
|
||||
if (_controlChannel != null &&
|
||||
_controlChannel!.state == RTCDataChannelState.RTCDataChannelOpen) {
|
||||
_controlChannel!.send(RTCDataChannelMessage.fromBinary(bytes));
|
||||
}
|
||||
}
|
||||
|
||||
/// 发送一次点击(相对坐标 0~1)。
|
||||
void sendTap(double relX, double relY) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.touch,
|
||||
x: relX,
|
||||
y: relY,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 发送长按。
|
||||
void sendLongPress(double relX, double relY) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.longPress,
|
||||
x: relX,
|
||||
y: relY,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 发送滑动。
|
||||
void sendSwipe(double relX1, double relY1, double relX2, double relY2, {int duration = 300}) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.swipe,
|
||||
x1: relX1,
|
||||
y1: relY1,
|
||||
x2: relX2,
|
||||
y2: relY2,
|
||||
duration: duration,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 发送实时触摸事件(MOTION_EVENT,跟手用)。action:0=DOWN,1=UP,2=MOVE。
|
||||
void sendMotionEvent(int action, double relX, double relY) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.motionEvent,
|
||||
x: relX,
|
||||
y: relY,
|
||||
motionAction: action,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 发送按键(keyAction:0=down,1=up;-1=点按)。
|
||||
void sendKey(int keyCode, {int keyAction = -1}) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.key,
|
||||
keyCode: keyCode,
|
||||
keyAction: keyAction,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 请求切换被控端采集分辨率。
|
||||
void sendSetResolution({int width = 0, int height = 0, int fps = 0}) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.setResolution,
|
||||
width: width,
|
||||
height: height,
|
||||
fps: fps,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 关闭连接。
|
||||
Future<void> dispose() async {
|
||||
try {
|
||||
if (_controlChannel != null) {
|
||||
await _controlChannel!.close();
|
||||
}
|
||||
if (_pc != null) {
|
||||
await _pc!.close();
|
||||
}
|
||||
await remoteRenderer.dispose();
|
||||
} catch (e) {
|
||||
debugPrint('[webrtc] dispose error: $e');
|
||||
}
|
||||
_controlChannel = null;
|
||||
_pc = null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user