feat: 真实连接链路、移除虚拟数据、全量打包脚本

This commit is contained in:
tongtong committed 2026-11-26 21:39:10 +08:00
1 parent 31b9a52eb4
commit 34340f4126
16 files changed
+601 -204

No files matched your search

+128 -78
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
@@ -24,31 +25,6 @@ class SenderBridge {
bool get isLocalSignalingRunning => _localSignaling.isRunning;
static const mockDevices = [
DeviceInfo(
id: 'demo-pixel',
name: '客厅 Pixel',
ip: '192.168.1.10',
mediaPort: 41000,
controlPort: 41001,
fingerprint: 'sha256:ab12cd34ef567890',
capabilities: ['h264', 'opus', 'uibc', 'clipboard', 'file'],
model: 'Pixel8',
resolution: '1920x1080',
),
DeviceInfo(
id: 'demo-tablet',
name: '书房平板',
ip: '192.168.1.23',
mediaPort: 42000,
controlPort: 42001,
fingerprint: 'sha256:9988776655443322',
capabilities: ['h265', 'opus', 'uibc'],
model: 'PadPro',
resolution: '2560x1600',
),
];
Stream<ConnectionPhase> watchPhase() {
return _events
.receiveBroadcastStream()
@@ -58,29 +34,148 @@ class SenderBridge {
}
Future<List<DeviceInfo>> discover() async {
if (_native != null) {
final localIp = await _localIp();
if (localIp == null) return const <DeviceInfo>[];
return [
DeviceInfo(
id: 'local-listener',
name: '本机监听端点',
ip: localIp,
mediaPort: 41000,
controlPort: 41001,
fingerprint: '',
capabilities: const <String>[],
model: '',
resolution: '',
),
];
}
try {
final raw = await _method.invokeListMethod<dynamic>('discover');
if (raw == null || raw.isEmpty) return mockDevices;
if (raw == null || raw.isEmpty) return const <DeviceInfo>[];
return DeviceInfo.listFromJson(raw);
} on MissingPluginException {
return mockDevices;
return const <DeviceInfo>[];
} on PlatformException {
return mockDevices;
return const <DeviceInfo>[];
}
}
static Future<String?> _localIp() async {
try {
final interfaces = await NetworkInterface.list(
includeLoopback: false,
type: InternetAddressType.IPv4,
);
for (final interface in interfaces) {
for (final address in interface.addresses) {
if (!address.isLoopback) return address.address;
}
}
} on Object {
// 忽略网络接口枚举失败。
}
return null;
}
Future<void> connect(DeviceInfo device) async {
final native = _native;
if (native != null) {
native.startDemoServer();
return;
}
await _invokeIgnoringMissing('connect', device.toJson());
}
Future<void> disconnect() async {
final native = _native;
if (native != null) {
native.stopDemoServer();
return;
}
await _invokeIgnoringMissing('disconnect');
}
Future<void> sendControl(String type, Map<String, dynamic> payload) async {
final native = _native;
if (native != null) {
final sequence = _controlSequence++;
final msgType = _msgTypeFor(type);
if (msgType == null) return;
final bytes = _controlPayload(type, msgType, payload);
if (bytes == null) return;
native.sendDemoControl(sequence, msgType, bytes);
return;
}
await _invokeIgnoringMissing('control', {'type': type, ...payload});
}
int _controlSequence = 1;
static int? _msgTypeFor(String type) {
switch (type) {
case 'touch':
return 0;
case 'mouse':
return 1;
case 'key':
return 2;
case 'wheel':
return 3;
case 'clipboard':
return 4;
case 'ping':
return 5;
default:
return null;
}
}
static List<int>? _controlPayload(String type, int msgType, Map<String, dynamic> payload) {
int byte(String key, [int fallback = 0]) {
final value = payload[key];
return value is num ? value.toInt() : fallback;
}
List<int> le16(int value) => [value & 0xff, (value >> 8) & 0xff];
switch (type) {
case 'touch':
return [
byte('action'),
byte('pointerId'),
...le16(byte('x')),
...le16(byte('y')),
...le16(byte('pressure')),
];
case 'mouse':
return [
byte('action'),
...le16(byte('x')),
...le16(byte('y')),
byte('buttons'),
];
case 'key':
return [byte('action'), ...le16(byte('keycode')), ...le16(byte('modifiers'))];
case 'wheel':
return [...le16(byte('deltaX')), ...le16(byte('deltaY')), byte('buttons')];
case 'clipboard':
return (payload['text'] as String? ?? '').codeUnits;
case 'ping':
final ts = byte('timestamp');
return [
ts & 0xff,
(ts >> 8) & 0xff,
(ts >> 16) & 0xff,
(ts >> 24) & 0xff,
0, 0, 0, 0,
];
default:
return null;
}
}
Future<void> saveSettings(AppSettings settings) async {
await _invokeIgnoringMissing('settings', settings.toJson());
}
@@ -98,46 +193,6 @@ class SenderBridge {
return settings.signalingUrl;
}
/// 通过 Rust Core 跑一次真实 ECDH + HKDF + AES-GCM + 媒体 MAC 自检。
Map<String, dynamic> runCryptoSelfTest() {
final native = _native;
if (native == null) {
return <String, dynamic>{'available': false, 'reason': 'Rust Core 未加载'};
}
final alice = native.generateKeyPair();
final bob = native.generateKeyPair();
try {
final aliceSecret = alice.agree(bob.publicBytes);
final bobSecret = bob.agree(alice.publicBytes);
final controlKey = native.deriveSubkey(aliceSecret, 'lancast/control/v1');
final videoKey = native.deriveSubkey(aliceSecret, 'lancast/video/v1');
final channel = native.createSecureChannel(controlKey);
final frame = channel.encodePing(1, DateTime.now().millisecondsSinceEpoch);
final decoded = channel.decode(frame);
channel.dispose();
final media = native.mediaEncode(
1234,
1,
videoKey,
const <int>[1, 2, 3, 4, 5],
);
final mediaDecoded = native.mediaDecode(media, videoKey);
return <String, dynamic>{
'available': true,
'ecdhMatch': aliceSecret.join() == bobSecret.join(),
'controlFrameBytes': frame.length,
'controlKind': decoded['kind'],
'mediaPacketBytes': media.length,
'mediaPts': mediaDecoded['pts'],
'controlKey': _hexPrefix(controlKey),
'videoKey': _hexPrefix(videoKey),
};
} finally {
alice.free();
bob.free();
}
}
/// 启动 Rust Core 的本机 demo 服务。
bool startDemoServer() =>
_native?.startDemoServer() ?? false;
@@ -147,28 +202,23 @@ class SenderBridge {
Map<String, dynamic> demoStatus() =>
_native?.demoStatus() ?? <String, dynamic>{'running': false};
static String _hexPrefix(List<int> bytes) => bytes
.take(4)
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
Future<String> pairingUri() async {
Future<String?> pairingUri() async {
try {
final value = await _method.invokeMethod<String>('pairingUri');
if (value != null && value.isNotEmpty) return value;
} on MissingPluginException {
// 桌面/测试环境没有原生桥时给出可扫描的示例 URI。
// 桌面端无原生配对桥。
} on PlatformException {
// 同上。
// 原生桥返回错误。
}
return 'lancast://pair?ip=192.168.1.10&port=41001&fp=sha256:ab12cd34ef567890';
return null;
}
Future<void> _invokeIgnoringMissing(String method, [Object? argument]) async {
try {
await _method.invokeMethod<void>(method, argument);
} on MissingPluginException {
// 测试或尚未接入 Rust Core 时使用 UI 演示数据。
// 当前平台没有原生实现,忽略该调用。
}
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ class AppSettings {
final int bitrateMbps;
const AppSettings({
this.signalingUrl = 'http://192.168.1.5:8080',
this.signalingUrl = '',
this.useLocalSignaling = true,
this.localSignalingEnabled = true,
this.localSignalingPort = 8080,
+17
View File
@@ -94,6 +94,9 @@ class NativeCore {
late final DartDemoStatusFn _demoStatus = _library
.lookup<NativeFunction<NativeDemoStatusFn>>('ttstd_demo_status')
.asFunction();
late final DartDemoSendControlFn _demoSendControl = _library
.lookup<NativeFunction<NativeDemoSendControlFn>>('ttstd_demo_send_control')
.asFunction();
bool get isAvailable => !_disposed;
@@ -181,6 +184,14 @@ class NativeCore {
});
}
bool sendDemoControl(int sequence, int msgType, List<int> payload) {
return _withBytes(payload, (ptr) {
final code = _demoSendControl(sequence, msgType, ptr, payload.length);
if (code < 0) throw NativeCoreException('ttstd_demo_send_control', code);
return true;
});
}
bool startDemoServer({int controlPort = 41001, int videoPort = 41000, int audioPort = 41002}) {
return _demoStart(controlPort, videoPort, audioPort) == ok;
}
@@ -378,3 +389,9 @@ typedef NativeDemoStopFn = Void Function();
typedef DartDemoStopFn = void Function();
typedef NativeDemoStatusFn = Int32 Function(Pointer<Uint8>, UintPtr);
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
typedef NativeDemoSendControlFn = Int32 Function(
Uint16, Uint8, Pointer<Uint8>, UintPtr,
);
typedef DartDemoSendControlFn = int Function(
int, int, Pointer<Uint8>, int,
);
@@ -5,7 +5,7 @@ class VideoView extends StatelessWidget {
super.key,
this.textureId,
this.connected = false,
this.resolution = '1920x1080',
this.resolution = '',
this.pts,
});
@@ -50,15 +50,16 @@ class VideoView extends StatelessWidget {
style: theme.textTheme.bodySmall),
],
),
Positioned(
top: 12,
left: 12,
child: _Badge(
icon: Icons.videocam,
label: resolution,
color: connected ? theme.colorScheme.primary : theme.colorScheme.outline,
if (resolution.isNotEmpty)
Positioned(
top: 12,
left: 12,
child: _Badge(
icon: Icons.videocam,
label: resolution,
color: connected ? theme.colorScheme.primary : theme.colorScheme.outline,
),
),
),
if (pts != null)
Positioned(
top: 12,
@@ -184,7 +184,7 @@ class _SettingsPageState extends State<SettingsPage> {
controller: _signalingUrl,
decoration: const InputDecoration(
labelText: '外部信令服务器',
hintText: 'http://192.168.1.5:8080',
hintText: 'http://<信令服务器IP>:8080',
prefixIcon: Icon(Icons.cloud),
border: OutlineInputBorder(),
),
+29 -71
View File
@@ -43,14 +43,13 @@ class _HomePageState extends State<HomePage> {
late final SenderBridge _bridge;
Timer? _demoStatusTimer;
List<DeviceInfo> _devices = SenderBridge.mockDevices;
DeviceInfo? _selected = SenderBridge.mockDevices.first;
List<DeviceInfo> _devices = const <DeviceInfo>[];
DeviceInfo? _selected;
ConnectionPhase _phase = ConnectionPhase.idle;
AppSettings _settings = AppSettings.defaults;
String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl;
bool _localSignalingRunning = false;
bool _refreshing = false;
Map<String, dynamic>? _selfTest;
Map<String, dynamic> _demoStatus = const <String, dynamic>{'running': false};
String? _nativeError;
@@ -68,7 +67,6 @@ class _HomePageState extends State<HomePage> {
});
_applySignalingSettings();
_refreshDevices();
_runSelfTest();
_demoStatusTimer = Timer.periodic(
const Duration(seconds: 1),
(_) => _refreshDemoStatus(),
@@ -84,41 +82,26 @@ class _HomePageState extends State<HomePage> {
super.dispose();
}
void _runSelfTest() {
if (_nativeCore == null) return;
try {
final result = _bridge.runCryptoSelfTest();
if (mounted) setState(() => _selfTest = result);
} on Object catch (error) {
if (mounted) setState(() => _nativeError = error.toString());
}
}
void _refreshDemoStatus() {
if (_nativeCore == null || !mounted) return;
try {
final status = _bridge.demoStatus();
setState(() => _demoStatus = status);
setState(() {
_demoStatus = status;
final running = status['running'] == true;
final connected = status['peerConnected'] == true;
final keyEstablished = status['keyEstablished'] == true;
if (running && connected && keyEstablished) {
_phase = ConnectionPhase.direct;
} else if (running && _phase != ConnectionPhase.idle) {
_phase = ConnectionPhase.probing;
}
});
} on Object catch (_) {
// 动态库不可用时忽略轮询错误。
}
}
void _toggleDemoServer() {
if (_nativeCore == null) return;
try {
final running = _demoStatus['running'] == true;
if (running) {
_bridge.stopDemoServer();
} else {
_bridge.startDemoServer();
}
_refreshDemoStatus();
} on Object catch (error) {
if (mounted) setState(() => _nativeError = error.toString());
}
}
Future<void> _applySignalingSettings() async {
if (_settings.localSignalingEnabled) {
final started = await _bridge.startLocalSignaling(_settings.localSignalingPort);
@@ -153,8 +136,6 @@ class _HomePageState extends State<HomePage> {
if (device == null) return;
setState(() => _phase = ConnectionPhase.probing);
await _bridge.connect(device);
if (!mounted) return;
setState(() => _phase = ConnectionPhase.direct);
}
Future<void> _disconnect() async {
@@ -178,6 +159,12 @@ class _HomePageState extends State<HomePage> {
Future<void> _showPairing() async {
final uri = await _bridge.pairingUri();
if (!mounted) return;
if (uri == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('当前平台不支持扫码配对')),
);
return;
}
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
@@ -298,16 +285,11 @@ class _HomePageState extends State<HomePage> {
);
}
Widget _buildNativeDemoCard() {
final native = _nativeCore;
final test = _selfTest;
Widget _buildConnectionStatusCard() {
final status = _demoStatus;
final running = status['running'] == true;
final connected = status['peerConnected'] == true;
final keyEstablished = status['keyEstablished'] == true;
final events = (status['events'] as List<dynamic>? ?? const <dynamic>[])
.map((item) => item.toString())
.toList();
final peerIp = (status['peerIp'] as String? ?? '').trim();
return Card(
child: Padding(
@@ -317,48 +299,24 @@ class _HomePageState extends State<HomePage> {
children: [
Row(
children: [
const Icon(Icons.bolt_outlined, size: 18),
const Icon(Icons.link, size: 18),
const SizedBox(width: 8),
const Text('Rust Core 协议自检', style: TextStyle(fontWeight: FontWeight.bold)),
const Spacer(),
if (native != null)
TextButton(
onPressed: _toggleDemoServer,
child: Text(running ? '停止 demo 服务' : '启动 demo 服务'),
),
const Text('连接状态', style: TextStyle(fontWeight: FontWeight.bold)),
],
),
const SizedBox(height: 8),
if (_nativeError != null)
Text(
_nativeError!,
style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12),
)
else if (native == null)
const Text('未加载 Rust Core 动态库(桌面端编译后自动可用)。')
else
Text(
'版本 ${native.versionString} · ABI ${native.abiRevision()} · '
'ECDH ${test?['ecdhMatch'] == true ? '一致' : '未验证'} · '
'控制帧 ${test?['controlFrameBytes'] ?? '-'} B · '
'媒体包 ${test?['mediaPacketBytes'] ?? '-'} B',
'被控端 ${connected ? '已连接' : '未连接'} · '
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' +
(peerIp.isEmpty ? '' : ' · 对端 $peerIp'),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 8),
Text(
'demo 服务:${running ? '运行中' : '已停止'} · '
'被控端 ${connected ? '已连接' : '未连接'} · '
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH'} · '
'密钥 ${status['controlKey'] ?? '----'}',
style: Theme.of(context).textTheme.bodySmall,
),
if (events.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
events.take(5).join('\n'),
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 11),
),
),
],
),
),
@@ -374,7 +332,7 @@ class _HomePageState extends State<HomePage> {
VideoView(
textureId: null,
connected: _phase.isConnected,
resolution: _selected?.resolution ?? '1920x1080',
resolution: _selected?.resolution ?? '',
),
const SizedBox(height: 16),
ConnectBar(
@@ -389,7 +347,7 @@ class _HomePageState extends State<HomePage> {
onEvent: _sendControl,
),
const SizedBox(height: 12),
_buildNativeDemoCard(),
_buildConnectionStatusCard(),
const SizedBox(height: 12),
Card(
child: Padding(