feat: improve desktop path selection and USB connection recovery
This commit is contained in:
1 parent
5aa575f182
commit
6490665af8
28 files changed
+846
-51
No files matched your search
@@ -5,11 +5,13 @@ import 'dart:io';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'windows_usb.dart';
|
||||
import 'usb_recovery.dart';
|
||||
|
||||
class Settings {
|
||||
String server = 'wss://ttstd.com/ads';
|
||||
String origin = '175.178.213.60:443';
|
||||
String credential = '';
|
||||
Map<String, String> agentPaths = {};
|
||||
String client = '', adb = '', scrcpy = '';
|
||||
bool relayOnly = false, usbMode = false;
|
||||
String usbip = UsbDriver.defaultUsbip();
|
||||
@@ -17,6 +19,7 @@ class Settings {
|
||||
'server': server,
|
||||
'origin': origin,
|
||||
'credential': credential,
|
||||
'agentPaths': agentPaths,
|
||||
'client': client,
|
||||
'adb': adb,
|
||||
'scrcpy': scrcpy,
|
||||
@@ -28,6 +31,7 @@ class Settings {
|
||||
server = j['server'] as String? ?? server;
|
||||
origin = j['origin'] as String? ?? origin;
|
||||
credential = j['credential'] as String? ?? credential;
|
||||
agentPaths = Map<String, String>.from(j['agentPaths'] as Map? ?? {});
|
||||
client = j['client'] as String? ?? client;
|
||||
adb = j['adb'] as String? ?? adb;
|
||||
scrcpy = j['scrcpy'] as String? ?? scrcpy;
|
||||
@@ -64,7 +68,16 @@ class Session {
|
||||
WindowsUsbSession? usb;
|
||||
String get endpoint => usb?.serial ?? tunnel;
|
||||
String get mode => usb == null ? "网络 ADB" : "虚拟 USB";
|
||||
final Process process;
|
||||
Process process;
|
||||
Future<Process> Function()? restartClient;
|
||||
final recovery = UsbRecoveryPolicy();
|
||||
String usbip = '', usbExecutable = '';
|
||||
bool recovering = false,
|
||||
initialized = false,
|
||||
screenWanted = false,
|
||||
usbBroken = false;
|
||||
Future<void>? recoveryTask;
|
||||
bool screenPageVisible = false;
|
||||
Process? screen;
|
||||
bool screenEmbedded = false;
|
||||
String state = '连接中', route = '协商中';
|
||||
@@ -77,6 +90,7 @@ class ManagerRepository {
|
||||
final Map<String, Session> sessions = {};
|
||||
final Set<int> reservedPorts = {};
|
||||
final void Function(String) log;
|
||||
bool allowEmbeddedResume = true;
|
||||
String token = '';
|
||||
Directory? root;
|
||||
late Directory storage;
|
||||
@@ -336,19 +350,24 @@ class ManagerRepository {
|
||||
'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json',
|
||||
);
|
||||
final lease = usbMode ? "$status.lease" : null;
|
||||
final proc = await Process.start(
|
||||
settings.client,
|
||||
final clientExecutable = settings.client, adbExecutable = settings.adb;
|
||||
final serverAddress = settings.server.trim(),
|
||||
originAddress = settings.origin.trim();
|
||||
final transportMode = settings.relayOnly ? 'relay' : 'auto';
|
||||
final clientEnvironment = environment()..['ADS_CLIENT_TOKEN'] = token;
|
||||
Future<Process> startClient() => Process.start(
|
||||
clientExecutable,
|
||||
[
|
||||
'--server',
|
||||
settings.server.trim(),
|
||||
serverAddress,
|
||||
'--device',
|
||||
id,
|
||||
'--listen',
|
||||
endpoint,
|
||||
'--adb',
|
||||
settings.adb,
|
||||
adbExecutable,
|
||||
'--transport',
|
||||
settings.relayOnly ? 'relay' : 'auto',
|
||||
transportMode,
|
||||
'--status-file',
|
||||
status,
|
||||
if (lease != null) ...[
|
||||
@@ -356,26 +375,21 @@ class ManagerRepository {
|
||||
'--lease-status-file',
|
||||
lease,
|
||||
],
|
||||
if (settings.origin.trim().isNotEmpty) ...[
|
||||
'--connect-address',
|
||||
settings.origin.trim(),
|
||||
],
|
||||
if (originAddress.isNotEmpty) ...['--connect-address', originAddress],
|
||||
],
|
||||
environment: environment()..['ADS_CLIENT_TOKEN'] = token,
|
||||
environment: clientEnvironment,
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
final proc = await startClient();
|
||||
watch(proc, id);
|
||||
session = Session(id, endpoint, settings.adb, status, proc);
|
||||
final current = session;
|
||||
sessions[id] = current;
|
||||
current.leaseFile = lease;
|
||||
unawaited(
|
||||
proc.exitCode.then((code) {
|
||||
current.exited = true;
|
||||
current.ready = false;
|
||||
current.state = '连接程序已退出 ($code)';
|
||||
}),
|
||||
);
|
||||
current.restartClient = startClient;
|
||||
current.usbip = usbip;
|
||||
current.usbExecutable = findTool('ads-usb');
|
||||
observeClient(current, proc);
|
||||
if (usbMode) {
|
||||
final usb = WindowsUsbSession(id, usbPort!);
|
||||
current.usb = usb;
|
||||
@@ -392,6 +406,7 @@ class ManagerRepository {
|
||||
);
|
||||
log('USB 已挂载:${usb.serial}');
|
||||
}
|
||||
current.initialized = true;
|
||||
return current;
|
||||
} catch (_) {
|
||||
if (session != null) {
|
||||
@@ -442,11 +457,11 @@ class ManagerRepository {
|
||||
Future<void> monitor() async {
|
||||
final listings = <String, String>{};
|
||||
for (final s in sessions.values.toList()) {
|
||||
if (!s.stopping && (s.exited || s.usb?.exited == true)) {
|
||||
if (s.usb == null && !s.stopping && s.exited) {
|
||||
await disconnect(s.id);
|
||||
continue;
|
||||
}
|
||||
if (s.stopping) {
|
||||
if (s.stopping || s.recovering || !s.initialized) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -458,6 +473,29 @@ class ManagerRepository {
|
||||
.where((r) => r.length >= 2 && r[0] == s.endpoint)
|
||||
.firstOrNull;
|
||||
s.ready = row?[1] == 'device';
|
||||
if (s.usb != null &&
|
||||
s.recovery.due(
|
||||
DateTime.now(),
|
||||
ready: s.ready,
|
||||
unauthorized: row?[1] == 'unauthorized',
|
||||
broken: s.exited || s.usb!.exited || s.usbBroken,
|
||||
)) {
|
||||
scheduleUsbRecovery(s);
|
||||
continue;
|
||||
}
|
||||
if (s.ready &&
|
||||
s.screenWanted &&
|
||||
(!s.screenEmbedded ||
|
||||
(s.screenPageVisible && allowEmbeddedResume)) &&
|
||||
s.screen == null &&
|
||||
!DateTime.now().isBefore(s.recovery.retryAt)) {
|
||||
s.recovery.attempted(DateTime.now());
|
||||
try {
|
||||
await screen(s, embedded: s.screenEmbedded);
|
||||
} catch (e) {
|
||||
log('[${s.id}] 恢复投屏失败:$e');
|
||||
}
|
||||
}
|
||||
s.state = row == null ? '等待设备 / 自动重连' : row[1];
|
||||
final file = File(s.statusFile);
|
||||
if (await file.exists()) {
|
||||
@@ -473,16 +511,107 @@ class ManagerRepository {
|
||||
}
|
||||
}
|
||||
|
||||
void observeClient(Session s, Process process) {
|
||||
unawaited(
|
||||
process.exitCode.then((code) {
|
||||
if (s.process != process) {
|
||||
return;
|
||||
}
|
||||
s.exited = true;
|
||||
s.ready = false;
|
||||
s.state = '连接程序已退出 ($code)';
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> stopScreen(Session s) async {
|
||||
s.screenWanted = false;
|
||||
final process = s.screen;
|
||||
s.screen = null;
|
||||
await stop(process);
|
||||
log('[${s.id}] 用户停止投屏,取消自动恢复');
|
||||
}
|
||||
|
||||
void scheduleUsbRecovery(Session s) {
|
||||
if (s.stopping || s.recovering) {
|
||||
return;
|
||||
}
|
||||
s.recovering = true;
|
||||
s.ready = false;
|
||||
s.recovery.attempted(DateTime.now());
|
||||
s.state = 'USB 会话中断 · 正在重新挂载';
|
||||
log('[${s.id}] USB 自动恢复,第 ${s.recovery.attempts} 次');
|
||||
s.recoveryTask = recoverUsb(s).whenComplete(() => s.recovering = false);
|
||||
}
|
||||
|
||||
Future<void> recoverUsb(Session s) async {
|
||||
try {
|
||||
final screen = s.screen;
|
||||
s.screen = null;
|
||||
await stop(screen);
|
||||
final old = s.usb!;
|
||||
await stop(old.bridge);
|
||||
reservedPorts.remove(old.port);
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
if (s.exited) {
|
||||
final lease = File(s.leaseFile!);
|
||||
if (await lease.exists()) {
|
||||
await lease.delete();
|
||||
}
|
||||
s.process = await s.restartClient!();
|
||||
s.exited = false;
|
||||
watch(s.process, s.id);
|
||||
observeClient(s, s.process);
|
||||
}
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
final port = await allocateUsbPort();
|
||||
final usb = WindowsUsbSession(s.id, port);
|
||||
s.usb = usb;
|
||||
await usb.start(
|
||||
leaseFile: s.leaseFile!,
|
||||
upstream: s.tunnel,
|
||||
executable: s.usbExecutable,
|
||||
usbip: s.usbip,
|
||||
environment: environment(),
|
||||
run: run,
|
||||
watch: watch,
|
||||
cancelled: () => s.stopping || s.exited,
|
||||
);
|
||||
s.usbBroken = false;
|
||||
s.recovery.missing = 0;
|
||||
s.state = 'USB 已重新挂载 · 等待 ADB 就绪';
|
||||
log('[${s.id}] USB 已重新挂载;设备就绪后恢复投屏');
|
||||
} catch (e) {
|
||||
// No unhandled async exception; monitor retries with bounded backoff.
|
||||
try {
|
||||
await stop(s.usb?.bridge);
|
||||
} catch (_) {}
|
||||
if (!s.stopping) {
|
||||
s.state = 'USB 恢复失败 · 稍后重试';
|
||||
log('[${s.id}] USB 恢复失败:$e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> screen(Session s, {bool embedded = false}) async {
|
||||
if (!s.ready) {
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
s.screenWanted = true;
|
||||
if (!s.ready || s.recovering || s.stopping) {
|
||||
return;
|
||||
}
|
||||
if (s.screen != null) {
|
||||
if (s.screenEmbedded == embedded) {
|
||||
return;
|
||||
}
|
||||
await stop(s.screen);
|
||||
final previous = s.screen;
|
||||
s.screen = null;
|
||||
await stop(previous);
|
||||
}
|
||||
final proc = await launchScreen(
|
||||
s.endpoint,
|
||||
@@ -490,6 +619,10 @@ class ManagerRepository {
|
||||
s.id,
|
||||
embedded: embedded,
|
||||
);
|
||||
if (s.stopping || !s.screenWanted) {
|
||||
await stop(proc);
|
||||
return;
|
||||
}
|
||||
s.screen = proc;
|
||||
s.screenEmbedded = embedded;
|
||||
watch(proc, 'scrcpy ${s.id}');
|
||||
@@ -497,6 +630,11 @@ class ManagerRepository {
|
||||
proc.exitCode.then((code) {
|
||||
if (s.screen == proc) {
|
||||
s.screen = null;
|
||||
if (code == 0) {
|
||||
s.screenWanted = false;
|
||||
} else if (!s.stopping && code == 2 && s.usb != null) {
|
||||
s.usbBroken = true;
|
||||
}
|
||||
}
|
||||
log('投屏窗口关闭 ($code)');
|
||||
}),
|
||||
@@ -549,6 +687,8 @@ class ManagerRepository {
|
||||
return;
|
||||
}
|
||||
s.stopping = true;
|
||||
s.screenWanted = false;
|
||||
await s.recoveryTask;
|
||||
for (final proc in [s.screen, s.usb?.bridge, s.process]) {
|
||||
try {
|
||||
await stop(proc);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/// Poll-based hysteresis and bounded retry delay, independent of processes/UI.
|
||||
class UsbRecoveryPolicy {
|
||||
int missing = 0, attempts = 0, stable = 0;
|
||||
DateTime retryAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
bool due(
|
||||
DateTime now, {
|
||||
required bool ready,
|
||||
bool unauthorized = false,
|
||||
bool broken = false,
|
||||
}) {
|
||||
if (unauthorized) {
|
||||
missing = 0;
|
||||
stable = 0;
|
||||
return false;
|
||||
}
|
||||
if (ready && !broken) {
|
||||
missing = 0;
|
||||
if (++stable >= 10) {
|
||||
attempts = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
stable = 0;
|
||||
missing++;
|
||||
return (broken || missing >= 3) && !now.isBefore(retryAt);
|
||||
}
|
||||
|
||||
void attempted(DateTime now) {
|
||||
final seconds = [2, 4, 8, 16, 30][attempts.clamp(0, 4)];
|
||||
attempts++;
|
||||
missing = 0;
|
||||
retryAt = now.add(Duration(seconds: seconds));
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ class UsbDriver {
|
||||
static const hash =
|
||||
'38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a';
|
||||
static String defaultUsbip() => p.join(
|
||||
Platform.environment['ProgramFiles'] ?? r'C:Program Files',
|
||||
Platform.environment['ProgramFiles'] ?? 'C:/Program Files',
|
||||
'USBip',
|
||||
'usbip.exe',
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user