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

@@ -10,13 +10,13 @@ import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.ttstd.lancast.receiver.session.PairingCode
import com.ttstd.lancast.receiver.session.TlsSession
import java.net.NetworkInterface
class MainActivity : Activity() {
companion object {
private const val REQUEST_CAPTURE = 1001
private const val FINGERPRINT = "sha256:ab12cd34ef567890"
const val EXTRA_HOST = "com.ttstd.lancast.receiver.HOST"
const val EXTRA_SIGNALING = "com.ttstd.lancast.receiver.SIGNALING"
}
private var session: ReceiverSession? = null
@@ -28,18 +28,29 @@ class MainActivity : Activity() {
super.onCreate(savedInstanceState)
status = TextView(this).apply { text = "状态:未开始" }
val initialHost = intent?.getStringExtra(EXTRA_HOST)?.takeIf { it.isNotBlank() } ?: ""
val initialSignaling = intent?.getStringExtra(EXTRA_SIGNALING)?.takeIf { it.isNotBlank() } ?: ""
hostInput = EditText(this).apply {
hint = "主控端 IP"
setText("192.168.1.5")
setText(initialHost)
}
signalingInput = EditText(this).apply {
hint = "信令服务器"
setText("http://192.168.1.5:8080")
hint = "信令服务器(可选)"
setText(initialSignaling)
}
val pairing = TextView(this).apply {
text = "配对码:\n${PairingCode.build(localIp(), 41001, FINGERPRINT)}"
text = "配对码:生成中..."
textSize = 13f
}
Thread {
val ip = try { localIp() } catch (_: Exception) { "" }
val text = if (ip.isEmpty()) {
"配对码:无法获取本机 IP"
} else {
"配对码:\n${PairingCode.build(ip, 41001, "")}"
}
runOnUiThread { pairing.text = text }
}.start()
val start = Button(this).apply { text = "授权并开始投屏" }
val stop = Button(this).apply { text = "停止" }
@@ -55,6 +66,10 @@ class MainActivity : Activity() {
})
start.setOnClickListener {
if (hostInput.text.toString().trim().isEmpty()) {
Toast.makeText(this, "请先填写主控端 IP", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val manager = getSystemService(MediaProjectionManager::class.java)
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
}
@@ -81,8 +96,15 @@ class MainActivity : Activity() {
signalingUrl = signalingInput.text.toString().trim(),
certificatePem = "",
)
session?.start()
status.text = "状态:采集中 · 指纹 ${TlsSession.sha256Hex(FINGERPRINT.toByteArray()).take(16)}"
status.text = "状态:连接中..."
Thread {
try {
session?.start()
runOnUiThread { status.text = "状态:采集中" }
} catch (error: Exception) {
runOnUiThread { status.text = "状态:连接失败 - ${error.message}" }
}
}.start()
}
override fun onDestroy() {
@@ -94,5 +116,5 @@ class MainActivity : Activity() {
private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
?.hostAddress ?: "192.168.1.10"
?.hostAddress ?: ""
}
@@ -16,7 +16,6 @@ import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.session.ReceiverTransport
import com.ttstd.lancast.receiver.session.TlsSession
import java.io.File
import java.util.UUID
import java.util.concurrent.Executors
@@ -35,7 +34,7 @@ class ReceiverSession(
private val injector = InputInjector(context)
private val fileService = FileService(File(context.filesDir, "file-inbox"))
private val opusEncoder = OpusEncoder()
private val fingerprint = TlsSession.sha256Hex(certificatePem.toByteArray()).take(16)
private val fingerprint: String = ""
private val transport = ReceiverTransport(
host,
41001,
@@ -117,5 +116,5 @@ class ReceiverSession(
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address }
?.hostAddress ?: "192.168.1.10"
?.hostAddress ?: ""
}
+22
View File
@@ -0,0 +1,22 @@
android {
signingConfigs {
create("keypub") {
storeFile = file("E:/TongTongStudio/TTSTD/key/keypub.jks")
storePassword = "123456"
keyAlias = "publickey"
keyPassword = "123456"
}
create("crosshatch") {
storeFile = file("E:/TongTongStudio/TTSTD/key/AospCrosshatch.keystore")
storePassword = "Fan1996"
keyAlias = "AospCrosshatch"
keyPassword = "Fan1996"
}
create("zhanxun") {
storeFile = file("E:/TongTongStudio/TTSTD/key/zhanxun.keystore")
storePassword = "123456"
keyAlias = "zhanxun"
keyPassword = "123456"
}
}
}
+29
View File
@@ -36,6 +36,35 @@ cargo test --offline --test demo_e2e
运行前确保 `ttstdconnect_core.dll`(Windows)/ `.so`(Linux)位于可执行文件同目录;`installer/windows/package.ps1` 已自动构建并内置该动态库。
## 非同一局域网的模拟器测试
当被控端与主控端不在同一局域网时,可用 Android 模拟器 + `adb reverse` 把电脑端口映射到模拟器:
```powershell
# 1. 启动模拟器(已有 Pixel_8 AVD)
& "F:\AndroidSDK\emulator\emulator.exe" -avd Pixel_8 -no-snapshot-load
# 2. 端口反向映射:模拟器访问 127.0.0.1:41001 即电脑的 41001
$adb = "F:\AndroidSDK\platform-tools\adb.exe"
& $adb -s emulator-5554 reverse tcp:41001 tcp:41001
& $adb -s emulator-5554 reverse tcp:41000 tcp:41000
& $adb -s emulator-5554 reverse tcp:41002 tcp:41002
# 3. 电脑上运行 demo 服务
cd rust_core
cargo run --example demo_server
# 4. 在模拟器启动被控端(host 用 127.0.0.1)
& $adb -s emulator-5554 shell am start -n com.ttstd.lancast.receiver/.MainActivity `
--es com.ttstd.lancast.receiver.HOST 127.0.0.1
# 5. 点击「测试连接(无需授权)」按钮,跳过 MediaProjection 授权只验证连接
```
成功标志:demo 服务日志出现 `peer:127.0.0.1:xxxxx` 与 `key-established`,模拟器界面显示「状态:ECDH 已建立(测试模式)」。
注意:crosshatch 系统签名 APK 可安装在 userdebug/eng 构建的模拟器上;普通零售系统镜像请改用 neutral 变体。
## Android 被控端
```powershell
+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(
+50 -16
View File
@@ -1,20 +1,34 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:ttstd_sender/core/bridge.dart';
import 'package:ttstd_sender/core/models.dart';
import 'package:ttstd_sender/main.dart';
const MethodChannel _methodChannel = MethodChannel('ttstd/sender');
const EventChannel _eventChannel = EventChannel('ttstd/sender/events');
void _mockChannels() {
const Duration _settleTimeout = Duration(seconds: 5);
DeviceInfo _testDevice() => const DeviceInfo(
id: 'test-device-1',
name: '测试被控端',
ip: '10.0.0.2',
mediaPort: 41000,
controlPort: 41001,
fingerprint: 'test-fingerprint',
capabilities: ['h264'],
model: 'TestModel',
resolution: '1280x720',
);
void _mockChannels({List<DeviceInfo> devices = const [], String? pairingUri}) {
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(_methodChannel, (call) async {
switch (call.method) {
case 'discover':
return SenderBridge.mockDevices.map((device) => device.toJson()).toList();
return devices.map((device) => device.toJson()).toList();
case 'pairingUri':
return 'lancast://pair?ip=192.168.1.10&port=41001&fp=sha256:ab12cd34ef567890';
return pairingUri;
default:
return null;
}
@@ -32,47 +46,67 @@ void main() {
messenger.setMockStreamHandler(_eventChannel, null);
});
testWidgets('首页展示设备列表与连接工具栏', (tester) async {
testWidgets('首页无设备时显示空态', (tester) async {
_mockChannels();
await tester.pumpWidget(const TTSTDConnectApp());
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('TTSTD Connect'), findsOneWidget);
expect(find.text('客厅 Pixel'), findsOneWidget);
expect(find.text('可连接设备'), findsOneWidget);
});
testWidgets('首页展示设备列表与连接工具栏', (tester) async {
_mockChannels(devices: [_testDevice()]);
await tester.pumpWidget(const TTSTDConnectApp());
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('测试被控端'), findsOneWidget);
expect(find.text('可连接设备'), findsOneWidget);
expect(find.byIcon(Icons.play_arrow), findsOneWidget);
await tester.tap(find.byIcon(Icons.refresh));
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('可连接设备'), findsOneWidget);
});
testWidgets('扫码配对对话框展示 pairing URI', (tester) async {
_mockChannels();
testWidgets('扫码配对对话框展示原生返回的 pairing URI', (tester) async {
const uri = 'lancast://pair?ip=10.0.0.2&port=41001&fp=test-fingerprint';
_mockChannels(pairingUri: uri);
await tester.pumpWidget(const TTSTDConnectApp());
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
await tester.tap(find.byIcon(Icons.qr_code_scanner));
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('扫码配对'), findsOneWidget);
expect(find.textContaining('lancast://pair?'), findsOneWidget);
expect(find.text(uri), findsOneWidget);
});
testWidgets('配对码不可用时提示而不展示假 URI', (tester) async {
_mockChannels();
await tester.pumpWidget(const TTSTDConnectApp());
await tester.pumpAndSettle(_settleTimeout);
await tester.tap(find.byIcon(Icons.qr_code_scanner));
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('当前平台不支持扫码配对'), findsOneWidget);
});
testWidgets('设置页可切换本机信令与外部信令', (tester) async {
_mockChannels();
await tester.pumpWidget(const TTSTDConnectApp());
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
await tester.tap(find.byIcon(Icons.settings));
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('使用本机信令服务器'), findsOneWidget);
expect(find.text('开启本机信令服务'), findsOneWidget);
expect(find.textContaining('本机地址:http://'), findsOneWidget);
await tester.tap(find.text('使用本机信令服务器'));
await tester.pumpAndSettle();
await tester.pumpAndSettle(_settleTimeout);
expect(find.text('外部信令服务器'), findsOneWidget);
});
+81 -15
View File
@@ -1,3 +1,7 @@
param(
[switch]$SkipClean # 增量打包:跳过 clean,只重新 build
)
$ErrorActionPreference = "Stop"
$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
@@ -5,6 +9,7 @@ $flutterDir = Join-Path $root "flutter_sender"
$signalDir = Join-Path $root "signaling_server"
$rustDir = Join-Path $root "rust_core"
$dist = Join-Path $root "dist\TTSTDConnect-Windows"
$flutterOutput = Join-Path $flutterDir "build\windows\x64\runner\Release"
foreach ($required in @($flutterDir, $signalDir, $rustDir)) {
if (-not (Test-Path $required)) {
@@ -12,29 +17,90 @@ foreach ($required in @($flutterDir, $signalDir, $rustDir)) {
}
}
Write-Host "Building Flutter Windows app..."
Push-Location $flutterDir
flutter build windows --release
Pop-Location
# 停掉从 dist 或各构建目录运行的进程(会锁定 exe/dll,导致 clean 或复制失败)。
$ownedDirs = @(
$dist,
(Join-Path $rustDir "target"),
$flutterOutput
)
Get-Process -ErrorAction SilentlyContinue | Where-Object {
$process = $_
$process.Path -and ($ownedDirs | Where-Object { $process.Path.StartsWith($_, [System.StringComparison]::OrdinalIgnoreCase) })
} | ForEach-Object {
Write-Host "Stopping process using build output: $($_.ProcessName) ($($_.Id))"
Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
}
Start-Sleep -Milliseconds 500
New-Item -ItemType Directory -Force -Path $dist | Out-Null
$flutterOutput = Join-Path $flutterDir "build\windows\x64\runner\Release"
Copy-Item -Recurse -Force (Join-Path $flutterOutput "*") $dist
function Invoke-BuildStep([string]$description, [string]$directory, [string[]]$arguments) {
Write-Host "=== $description ==="
Push-Location $directory
try {
& $arguments[0] @($arguments[1..($arguments.Count - 1)])
if ($LASTEXITCODE -ne 0) {
throw "$description failed with exit code $LASTEXITCODE"
}
} finally {
Pop-Location
}
}
Write-Host "Building embedded signaling server..."
Push-Location $signalDir
go build -o (Join-Path $dist "signaling_server.exe") .
Pop-Location
if (-not $SkipClean) {
Write-Host "=== Cleaning all build artifacts ==="
Invoke-BuildStep "Cleaning Flutter" $flutterDir @("flutter", "clean")
Invoke-BuildStep "Cleaning Rust" $rustDir @("cargo", "clean")
Invoke-BuildStep "Cleaning Go" $signalDir @("go", "clean")
Write-Host "Building Rust Core cdylib..."
Push-Location $rustDir
cargo build --release
Pop-Location
if (Test-Path $dist) {
Remove-Item -Recurse -Force $dist
}
}
Invoke-BuildStep "Building Rust Core cdylib" $rustDir @("cargo", "build", "--release")
$coreDll = Join-Path $rustDir "target\release\ttstdconnect_core.dll"
if (-not (Test-Path $coreDll)) {
throw "Rust Core dynamic library not found: $coreDll"
}
Invoke-BuildStep "Building Flutter Windows app" $flutterDir @("flutter", "build", "windows", "--release")
if (-not (Test-Path (Join-Path $flutterOutput "ttstd_sender.exe"))) {
throw "Flutter Windows build output not found: $flutterOutput"
}
# flutter build 不会复制外部 cdylib,这里补一次。
Copy-Item -Force $coreDll (Join-Path $flutterOutput "ttstdconnect_core.dll")
Invoke-BuildStep "Building embedded signaling server" $signalDir @("go", "build", "-o", (Join-Path $signalDir "signaling_server.exe"), ".")
$signalExe = Join-Path $signalDir "signaling_server.exe"
if (-not (Test-Path $signalExe)) {
throw "Signaling server binary not found: $signalExe"
}
Write-Host "=== Assembling package ==="
if (Test-Path $dist) {
Remove-Item -Recurse -Force $dist
}
New-Item -ItemType Directory -Force -Path $dist | Out-Null
Copy-Item -Recurse -Force (Join-Path $flutterOutput "*") $dist
Copy-Item -Force $signalExe (Join-Path $dist "signaling_server.exe")
Copy-Item -Force $coreDll (Join-Path $dist "ttstdconnect_core.dll")
# 校验所有核心文件与构建输出哈希一致,避免旧文件残留。
$pairs = @(
@((Join-Path $flutterOutput "ttstd_sender.exe"), (Join-Path $dist "ttstd_sender.exe")),
@((Join-Path $flutterOutput "data\app.so"), (Join-Path $dist "data\app.so")),
@($signalExe, (Join-Path $dist "signaling_server.exe")),
@($coreDll, (Join-Path $dist "ttstdconnect_core.dll"))
)
foreach ($pair in $pairs) {
$source = $pair[0]
$target = $pair[1]
if (-not (Test-Path $source) -or -not (Test-Path $target)) {
throw "Packaging file missing: source=$source target=$target"
}
if ((Get-FileHash $source -Algorithm SHA256).Hash -ne (Get-FileHash $target -Algorithm SHA256).Hash) {
throw "Packaged file does not match build output: $target"
}
}
Write-Host "Package ready: $dist"
Write-Host "Mode: full rebuild. Use -SkipClean for incremental packaging."
Write-Host "Default mode: local signaling on port 8080. Use Settings to disable it or switch to an external server."
+24
View File
@@ -0,0 +1,24 @@
//! 运行本机 demo 服务,供 Android 被控端反连测试。
//! cargo run --example demo_server
use std::thread;
use std::time::Duration;
use ttstdconnect_core::demo_server;
fn main() {
demo_server::start(41001, 41000, 41002).expect("启动 demo 服务失败");
println!("demo server listening: TCP 41001, UDP 41000/41002");
loop {
thread::sleep(Duration::from_secs(1));
let status = demo_server::status();
if !status.events.is_empty() {
for event in &status.events {
println!("[event] {}", event);
}
// 事件会累积,这里只打印最新一批后清空显示(服务内部保留全部)。
std::io::Write::flush(&mut std::io::stdout()).ok();
}
thread::sleep(Duration::from_secs(2));
}
}
+100 -1
View File
@@ -7,12 +7,18 @@
//! 4. 视频/音频通过 UDP 41000/41002 发送,使用 `MediaPackets` 的 13 字节头 + 4 字节 HMAC。
use std::io::{Read, Write};
use std::net::{TcpListener, UdpSocket};
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use crate::control::events::{
ClipboardEvent, KeyAction, KeyboardEvent, MouseAction, MouseEvent, TouchAction, TouchEvent,
WheelEvent,
};
use crate::control::{ControlEvent, ControlEventKind};
use crate::control::SecureControlChannel;
use crate::crypto::{derive_subkey, EphemeralKeyPair};
use crate::media::decode_media_packet;
@@ -61,6 +67,11 @@ impl DemoStatus {
}
}
struct ControlSender {
stream: Arc<Mutex<TcpStream>>,
channel: SecureControlChannel,
}
struct Shared {
running: AtomicBool,
peer_connected: AtomicBool,
@@ -69,6 +80,7 @@ struct Shared {
control_key: Mutex<Option<[u8; 32]>>,
video_key: Mutex<Option<[u8; 32]>>,
audio_key: Mutex<Option<[u8; 32]>>,
sender: Mutex<Option<ControlSender>>,
events: Mutex<Vec<String>>,
}
@@ -82,6 +94,7 @@ impl Shared {
control_key: Mutex::new(None),
video_key: Mutex::new(None),
audio_key: Mutex::new(None),
sender: Mutex::new(None),
events: Mutex::new(Vec::new()),
}
}
@@ -187,6 +200,81 @@ pub fn status() -> DemoStatus {
server_handle().shared.status()
}
/// 把控制事件编码为 AES-GCM 帧并下发给当前被控端。
/// 返回 Ok(()) 表示已写入 TCP,Err 表示未连接或写入失败。
pub fn send_control(event: ControlEvent) -> Result<(), String> {
let handle = server_handle();
let sender = handle
.shared
.sender
.lock()
.map_err(|_| "控制通道锁不可用".to_string())?;
let sender = sender.as_ref().ok_or_else(|| "没有已连接的被控端".to_string())?;
let frame = sender
.channel
.encode(&event)
.map_err(|error| format!("控制帧加密失败:{}", error))?;
let mut stream = sender
.stream
.lock()
.map_err(|_| "控制写端锁不可用".to_string())?;
stream
.write_all(&frame)
.and_then(|_| stream.flush())
.map_err(|error| format!("控制帧下发失败:{}", error))?;
handle.shared.push_event(format!(
"sent:seq={}:type={}",
event.sequence(),
event.msg_type()
));
Ok(())
}
/// 构造触摸控制事件。
pub fn touch_event(sequence: u16, action: u8, pointer_id: u8, x: i16, y: i16, pressure: u16) -> Option<ControlEvent> {
Some(ControlEvent::new(sequence, ControlEventKind::Touch(TouchEvent {
action: TouchAction::from_u8(action)?,
pointer_id,
x,
y,
pressure,
})))
}
/// 构造按键控制事件。
pub fn key_event(sequence: u16, action: u8, keycode: u16, modifiers: u16) -> Option<ControlEvent> {
Some(ControlEvent::new(sequence, ControlEventKind::Key(KeyboardEvent {
action: KeyAction::from_u8(action)?,
keycode,
modifiers,
})))
}
/// 构造鼠标控制事件。
pub fn mouse_event(sequence: u16, action: u8, x: i16, y: i16, buttons: u8) -> Option<ControlEvent> {
Some(ControlEvent::new(sequence, ControlEventKind::Mouse(MouseEvent {
action: MouseAction::from_u8(action)?,
x,
y,
buttons,
})))
}
/// 构造滚轮控制事件。
pub fn wheel_event(sequence: u16, delta_x: i16, delta_y: i16, buttons: u8) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Wheel(WheelEvent { delta_x, delta_y, buttons }))
}
/// 构造剪贴板控制事件。
pub fn clipboard_event(sequence: u16, text: String) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Clipboard(ClipboardEvent { text }))
}
/// 构造 Ping 控制事件。
pub fn ping_event(sequence: u16, timestamp: u64) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Ping(timestamp))
}
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
while shared.running.load(Ordering::Relaxed) {
match listener.accept() {
@@ -202,6 +290,9 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
handle_peer(&mut stream, &shared);
shared.peer_connected.store(false, Ordering::Relaxed);
shared.key_established.store(false, Ordering::Relaxed);
if let Ok(mut guard) = shared.sender.lock() {
*guard = None;
}
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(50));
@@ -258,6 +349,14 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
let _ = stream.flush();
let channel = SecureControlChannel::new(control);
if let Ok(write_stream) = stream.try_clone() {
if let Ok(mut guard) = shared.sender.lock() {
*guard = Some(ControlSender {
stream: Arc::new(Mutex::new(write_stream)),
channel: SecureControlChannel::new(control),
});
}
}
let mut buffer = Vec::new();
let mut chunk = [0u8; 4096];
while shared.running.load(Ordering::Relaxed) {
+59
View File
@@ -310,6 +310,65 @@ pub unsafe extern "C" fn ttstd_control_decode(
copy_out(json.as_bytes(), out_json, capacity)
}
/// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。
/// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE)
#[no_mangle]
pub unsafe extern "C" fn ttstd_demo_send_control(
sequence: u16,
msg_type: u8,
payload: *const u8,
payload_len: usize,
) -> i32 {
use crate::control::events::MSG_CLIPBOARD;
let bytes = match read_slice(payload, payload_len) {
Ok(value) => value,
Err(code) => return code,
};
let event = match msg_type {
0 if bytes.len() == 8 => crate::demo_server::touch_event(
sequence, bytes[0], bytes[1],
i16::from_le_bytes([bytes[2], bytes[3]]),
i16::from_le_bytes([bytes[4], bytes[5]]),
u16::from_le_bytes([bytes[6], bytes[7]]),
),
1 if bytes.len() == 6 => crate::demo_server::mouse_event(
sequence, bytes[0],
i16::from_le_bytes([bytes[1], bytes[2]]),
i16::from_le_bytes([bytes[3], bytes[4]]),
bytes[5],
),
2 if bytes.len() == 5 => crate::demo_server::key_event(
sequence, bytes[0],
u16::from_le_bytes([bytes[1], bytes[2]]),
u16::from_le_bytes([bytes[3], bytes[4]]),
),
3 if bytes.len() == 5 => Some(crate::demo_server::wheel_event(
sequence,
i16::from_le_bytes([bytes[0], bytes[1]]),
i16::from_le_bytes([bytes[2], bytes[3]]),
bytes[4],
)),
MSG_CLIPBOARD => Some(crate::demo_server::clipboard_event(
sequence,
String::from_utf8_lossy(bytes).to_string(),
)),
5 if bytes.len() == 8 => Some(crate::demo_server::ping_event(
sequence,
u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]),
)),
_ => None,
};
match event {
Some(event) => match crate::demo_server::send_control(event) {
Ok(()) => OK,
Err(_) => ERR_INVALID_ARGUMENT,
},
None => ERR_INVALID_ARGUMENT,
}
}
/// 启动本机 demo 服务:TCP 控制 + UDP 视频/音频。
#[no_mangle]
pub extern "C" fn ttstd_demo_start(control_port: u16, video_port: u16, audio_port: u16) -> i32 {
+17
View File
@@ -58,6 +58,23 @@ fn demo_server_handshake_control_and_media_roundtrip() {
assert_eq!(pong.sequence(), 1);
assert!(matches!(pong.kind, ControlEventKind::Pong(1234)));
// 主控端主动下发一个 Ping,被控端应能解密并识别。
demo_server::send_control(ControlEvent::new(
99,
ControlEventKind::Ping(4321),
))
.expect("下发控制帧");
let mut downlink = [0u8; 512];
let downlink_size = control
.read(&mut downlink)
.expect("读取主控端下发的控制帧");
let (downlink_event, _) = channel
.decode(&downlink[..downlink_size])
.expect("解密下发控制帧")
.expect("完整的下发控制帧");
assert_eq!(downlink_event.sequence(), 99);
assert!(matches!(downlink_event.kind, ControlEventKind::Ping(4321)));
let video = UdpSocket::bind("127.0.0.1:0").expect("创建视频 UDP");
let video_packet = encode_media_packet(
&MediaPacket {