feat: manage multiple desktop device connections independently

This commit is contained in:
tongtong committed 2026-11-12 18:15:04 +08:00
1 parent 08d60de364
commit 05d4d5fea6
12 files changed
+504 -249

No files matched your search

+137 -231
View File
@@ -8,9 +8,9 @@ using CommunityToolkit.Mvvm.Input;
namespace Ads.Desktop;
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal)
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal, bool Online = true, string LocalSummary = "")
{
public string Description => IsLocal ? "本机正在使用" : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
public string Description => IsLocal ? "本机 · " + LocalSummary : !Online ? "远程暂时离线" : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
}
public partial class MainViewModel : ObservableObject, IDisposable
@@ -55,13 +55,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
public ObservableCollection<DeviceItem> Devices { get; } = new();
public ObservableCollection<string> Logs { get; } = new();
public string? Endpoint => endpoint;
public string? ActiveDeviceId => activeId;
public ObservableCollection<DeviceConnection> Connections { get; } = new();
public string ConnectionSummary => $"{Connections.Count} 台连接 · {Connections.Count(c => c.Ready)} 台就绪 · {Connections.Count(c => c.ScreenRunning)} 台投屏";
public bool HasConnections => Connections.Count > 0;
public string? Endpoint => Current?.Endpoint;
public string? ActiveDeviceId => Current?.HasConnection == true ? Current.DeviceId : null;
public DeviceConnection? Current => SelectedDevice != null ? sessions.GetValueOrDefault(SelectedDevice.Id) : null;
private WindowsUsbSession? usbSession;
private string? leaseFile;
private Process? client, scrcpy;
private string? endpoint, rawEndpoint, activeAdb, activeId, transportFile;
private readonly Dictionary<string, DeviceConnection> sessions = new(StringComparer.Ordinal);
private string credentialFile = "", preferredDevice = "home-phone";
private bool monitoring, disposed, initialized;
private DateTime lastRefresh;
@@ -115,7 +116,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (value.Length > 0) lock (secrets) secrets.Add(value);
CredentialSource = value.Length > 0 ? "当前输入的客户端令牌(仅内存)" : "未加载客户端凭据";
}
partial void OnSelectedDeviceChanged(DeviceItem? value) => UpdateCommands();
partial void OnSelectedDeviceChanged(DeviceItem? value) => SyncSelected();
partial void OnHasConnectionChanged(bool value) => UpdateCommands();
partial void OnReadyChanged(bool value) => UpdateCommands();
partial void OnScreenRunningChanged(bool value) => UpdateCommands();
@@ -127,7 +128,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
ConnectCommand.NotifyCanExecuteChanged(); DisconnectCommand.NotifyCanExecuteChanged();
ReconnectCommand.NotifyCanExecuteChanged(); ReadDeviceInfoCommand.NotifyCanExecuteChanged();
StartScrcpyCommand.NotifyCanExecuteChanged(); StopScrcpyCommand.NotifyCanExecuteChanged();
ClearPortCommand.NotifyCanExecuteChanged();
ClearPortCommand.NotifyCanExecuteChanged(); ConnectAllCommand.NotifyCanExecuteChanged();
DisconnectAllCommand.NotifyCanExecuteChanged(); StartAllScreensCommand.NotifyCanExecuteChanged();
DisconnectDeviceCommand.NotifyCanExecuteChanged(); ReconnectDeviceCommand.NotifyCanExecuteChanged();
StartScreenDeviceCommand.NotifyCanExecuteChanged(); StopScreenDeviceCommand.NotifyCanExecuteChanged();
}
private string Redact(string text)
@@ -192,9 +196,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
var options = RelayOptions.Parse(Server, Origin, Token);
var rows = await RelayApi.GetDevicesAsync(options, lifetime.Token);
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
var selectedId = SelectedDevice?.Id ?? activeId ?? preferredDevice;
var selectedId = SelectedDevice?.Id ?? preferredDevice;
Devices.Clear();
foreach (var row in rows) Devices.Add(new DeviceItem(row.Id, row.Busy, HasConnection && row.Id == activeId));
foreach (var row in rows) {
var connection = sessions.GetValueOrDefault(row.Id);
Devices.Add(new DeviceItem(row.Id, row.Busy || connection?.HasConnection == true, connection?.HasConnection == true, true, connection?.Status ?? ""));
}
foreach (var local in Connections.Where(c => rows.All(r => r.Id != c.DeviceId)))
Devices.Add(new DeviceItem(local.DeviceId, true, true, false, local.Status));
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selectedId) ?? Devices.FirstOrDefault(d => !d.Busy) ?? Devices.FirstOrDefault();
RelayOnline = true;
RelayStatus = "控制中心在线";
@@ -219,24 +228,28 @@ public partial class MainViewModel : ObservableObject, IDisposable
finally { IsRefreshing = false; }
}
private bool CanConnect() => !IsWorking && !HasConnection && RelayOnline && SelectedDevice is { Busy: false };
private bool CanConnect() => !IsWorking && !HasConnection && RelayOnline && SelectedDevice is { Busy: false, Online: true };
private bool CanDisconnect() => !IsWorking && HasConnection;
private bool CanReadDeviceInfo() => !IsWorking && Ready;
private bool CanStartScrcpy() => !IsWorking && Ready && !ScreenRunning;
private bool CanStopScrcpy() => ScreenRunning;
private bool CanStopScrcpy() => !IsWorking && ScreenRunning;
private bool CanConnectAll() => !IsWorking && RelayOnline && Devices.Any(d => d.Online && !d.Busy && !d.IsLocal);
private bool CanDisconnectAll() => !IsWorking && HasConnections;
private bool CanStartAllScreens() => !IsWorking && Connections.Any(c => c.Ready && !c.ScreenRunning);
private bool CanClearPort() => !IsWorking;
[RelayCommand(CanExecute = nameof(CanClearPort))]
private Task ClearPortAsync() => Guard(() => Exclusive(async () =>
{
var selectedPort = Port;
var selectedPort = Current?.HasConnection == true ? Current.Options.Port : Port;
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
var releasedOwnConnection = HasConnection && rawEndpoint == $"127.0.0.1:{selectedPort}";
var releasedUsb = releasedOwnConnection && usbSession != null;
var owned = Connections.FirstOrDefault(c => c.Options.Port == selectedPort);
var releasedOwnConnection = owned != null;
var releasedUsb = owned?.Options.UsbMode == true;
if (releasedOwnConnection)
{
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
await DisconnectCoreAsync();
await owned!.DisconnectAsync();
}
var owners = await Task.Run(() => LocalPortProcesses.Inspect(selectedPort), lifetime.Token);
PortCleanupStatus = owners.Count == 0 ? $"端口 {selectedPort} 没有监听进程。" :
@@ -275,252 +288,148 @@ public partial class MainViewModel : ObservableObject, IDisposable
private async Task ConnectCoreAsync(DeviceItem device)
{
if (client != null) throw new InvalidOperationException("请先断开当前连接。");
if (sessions.GetValueOrDefault(device.Id)?.HasConnection == true) throw new InvalidOperationException("该设备已经连接。");
if (device.Busy) throw new InvalidOperationException("设备已被其他客户端占用。");
if (Port is < 1024 or > 65535) throw new InvalidOperationException("本地端口范围为 1024–65535。");
var portCheck = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, Port);
try
{
portCheck.Server.ExclusiveAddressUse = true;
portCheck.Start();
}
catch (System.Net.Sockets.SocketException)
{
throw new InvalidOperationException($"本地端口 {Port} 已被占用,请修改端口或先停止另一个连接客户端。");
}
finally { portCheck.Stop(); }
if (UsbMode) {
if (UsbPort == Port) throw new InvalidOperationException("USB/IP 端口不能与 ADB 隧道端口相同。");
WindowsUsbSession.Validate(UsbipPath, UsbPort);
}
var relay = RelayOptions.Parse(Server, Origin, Token);
var clientExecutable = DesktopPaths.ResolveTool(ClientPath, "ads-client");
var client = DesktopPaths.ResolveTool(ClientPath, "ads-client");
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
var address = $"127.0.0.1:{Port}";
var info = ProcessTools.ClientStartInfo(clientExecutable, adb, relay, device.Id, address);
Directory.CreateDirectory(folder);
transportFile = Path.Combine(folder, "transport-" + Guid.NewGuid().ToString("N") + ".json");
info.ArgumentList.Add("--transport"); info.ArgumentList.Add(RelayOnly ? "relay" : "auto");
info.ArgumentList.Add("--status-file"); info.ArgumentList.Add(transportFile);
var reserved = ReservedPorts().ToHashSet();
var rawPort = ConnectionPorts.Allocate(Port, reserved); reserved.Add(rawPort);
int? usbPort = null;
if (UsbMode) {
leaseFile = Path.Combine(folder, "lease-" + Guid.NewGuid().ToString("N") + ".json");
info.ArgumentList.Add("--no-auto-connect");
info.ArgumentList.Add("--lease-status-file"); info.ArgumentList.Add(leaseFile);
}
TransportStatus = "正在协商连接路线";
client = Start(info);
rawEndpoint = address; endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
HasConnection = true; Ready = false;
UpdateLocalOwnership();
ActiveEndpoint = $"{device.Id} → {address}";
Status = "正在连接 · 等待设备就绪";
Notice = "连接已启动;首次使用时请在手机上允许调试。";
Model = AndroidVersion = ApiLevel = "—";
Log($"连接 {device.Id},本地 ADB 地址 {address}。");
if (UsbMode) {
usbSession = new WindowsUsbSession(device.Id);
try {
await usbSession.StartAsync(UsbipPath, UsbPort, address, leaseFile!, Log, lifetime.Token);
endpoint = usbSession.Serial; OnPropertyChanged(nameof(Endpoint));
ActiveEndpoint = $"{device.Id} → USB ADB · {endpoint}";
Notice = "USB 模拟已挂载,等待本机 ADB 枚举;首次使用可能需要手机授权。";
} catch { await DisconnectCoreAsync(); throw; }
usbPort = ConnectionPorts.Allocate(UsbPort, reserved);
WindowsUsbSession.Validate(UsbipPath, usbPort.Value);
}
if (sessions.Remove(device.Id, out var old)) { old.PropertyChanged -= ConnectionChanged; old.Dispose(); }
var session = new DeviceConnection(device.Id,
new ConnectionOptions(relay, client, adb, UsbMode, UsbipPath, RelayOnly, rawPort, usbPort, folder), Log, lifetime.Token);
sessions.Add(device.Id, session); session.PropertyChanged += ConnectionChanged;
preferredDevice = device.Id;
try { await session.ConnectAsync(); }
finally { UpdateLocalOwnership(); SyncSelected(); }
Notice = $"{device.Id} 已启动,其他设备连接保持运行。";
}
private void ConnectionChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (sender is not DeviceConnection session) return;
if (session.HasConnection && !Connections.Contains(session)) Connections.Add(session);
else if (!session.HasConnection) Connections.Remove(session);
if (e.PropertyName is nameof(DeviceConnection.HasConnection) or nameof(DeviceConnection.Status)) UpdateLocalOwnership();
if (Current == session) SyncSelected();
OnPropertyChanged(nameof(ConnectionSummary)); OnPropertyChanged(nameof(HasConnections)); UpdateCommands();
}
private void SyncSelected()
{
var current = Current;
HasConnection = current?.HasConnection == true; Ready = current?.Ready == true; ScreenRunning = current?.ScreenRunning == true;
Status = current?.Status ?? "尚未连接";
TransportStatus = current?.TransportStatus ?? "尚未建立数据通道";
Model = current?.Model ?? "—"; AndroidVersion = current?.AndroidVersion ?? "—"; ApiLevel = current?.ApiLevel ?? "—";
ActiveEndpoint = HasConnection ? $"{current!.DeviceId} → {current.Mode} · {current.Endpoint}" : "选择设备后建立本地 ADB 通道";
if (!string.IsNullOrEmpty(current?.Notice)) Notice = Redact(current.Notice);
OnPropertyChanged(nameof(Current)); OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId)); UpdateCommands();
}
private void UpdateLocalOwnership()
{
var selected = SelectedDevice?.Id;
for (var index = 0; index < Devices.Count; index++)
{
var device = Devices[index];
if (HasConnection && device.Id == activeId) Devices[index] = device with { Busy = true, IsLocal = true };
else if (device.IsLocal) Devices[index] = device with { Busy = false, IsLocal = false };
for (var i = 0; i < Devices.Count; i++) {
var row = Devices[i]; var session = sessions.GetValueOrDefault(row.Id);
var local = session?.HasConnection == true;
var replacement = row with { Busy = local || (!row.IsLocal && row.Busy), IsLocal = local, LocalSummary = local ? session!.Status : "" };
if (replacement != row) Devices[i] = replacement;
}
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selected);
}
private Process Start(ProcessStartInfo info)
{
var process = new Process { StartInfo = info };
process.OutputDataReceived += (_, line) => { if (line.Data != null) Log(line.Data); };
process.ErrorDataReceived += (_, line) => { if (line.Data != null) Log(line.Data); };
try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); return process; }
catch { process.Dispose(); throw; }
}
private async Task<string> AdbAsync(string adb, CancellationToken cancellation, params string[] arguments)
{
var result = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(adb, arguments), cancellation);
if (result.ExitCode != 0) throw new InvalidOperationException("ADB:" + result.Error.Trim());
return result.Output;
}
private async Task MonitorAsync()
{
if (monitoring || disposed || IsWorking) return;
if (monitoring || disposed) return;
monitoring = true;
try
{
if (scrcpy is { HasExited: true })
{
Log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false;
}
if (transportFile != null && File.Exists(transportFile))
{
try {
// One ADB listing per executable for the whole fleet, including unselected phones.
foreach (var group in Connections.ToArray().GroupBy(c => c.Options.Adb)) {
try {
using var state = JsonDocument.Parse(await File.ReadAllTextAsync(transportFile, lifetime.Token));
var root = state.RootElement;
var nodes = string.Join("、", root.GetProperty("nodes").EnumerateArray().Select(n => n.GetString()));
TransportStatus = root.GetProperty("transport").GetString() switch {
"p2p" => "P2P 直连 · 数据不经过中继",
"relay" => "中继连接 · " + nodes,
"mixed" => "P2P 与中继并用 · " + nodes,
"negotiating" => "正在协商连接路线",
_ => "等待 ADB 数据通道"
};
} catch (IOException) { } catch (JsonException) { }
}
if (usbSession is { HasExited: true }) {
await Exclusive(DisconnectCoreAsync);
Notice = "USB 模拟进程已退出,请查看日志后重连。";
}
var current = client;
if (current != null)
{
if (current.HasExited)
{
Notice = $"连接守护程序退出,代码 {current.ExitCode};可查看日志后重新连接。";
await Exclusive(DisconnectCoreAsync);
}
else if (endpoint is { } address && activeAdb is { } adb)
{
var text = await AdbAsync(adb, lifetime.Token, "devices");
if (client == current)
{
var row = text.Split('\n').Select(l => l.Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))
.FirstOrDefault(parts => parts.Length >= 2 && parts[0] == address);
var wasReady = Ready;
Ready = row?[1] == "device";
Status = row?[1] switch
{
"device" => "已连接 · 可调试和控制",
"unauthorized" => "等待手机允许此电脑调试",
"offline" => "设备离线 · 正在恢复连接",
_ => "正在恢复连接 · 等待设备或网络"
};
if (Ready && !wasReady) { Log("设备已就绪。"); await ReadDeviceInfoCoreAsync(); }
}
var listing = await AdbAsync(group.Key, lifetime.Token, "devices");
await Task.WhenAll(group.Select(c => c.MonitorAsync(listing)));
} catch (Exception error) when (!lifetime.IsCancellationRequested) {
foreach (var connection in group) connection.MonitoringFailed(error.Message);
}
}
if (AutoRefresh && Token.Length >= 32 && DateTime.UtcNow - lastRefresh >= TimeSpan.FromSeconds(10))
{
if (AutoRefresh && Token.Length >= 32 && DateTime.UtcNow - lastRefresh >= TimeSpan.FromSeconds(10)) {
try { await RefreshDevicesAsync(announce: false); }
catch (Exception error)
{
catch (Exception error) {
var message = Redact(error.Message);
if (message != lastRefreshError) { Log("刷新设备:" + message); lastRefreshError = message; }
}
}
}
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
catch (Exception error) { if (!disposed) { Ready = false; Report(error); } }
} catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
catch (Exception error) { if (!disposed) Report(error); }
finally { monitoring = false; }
}
[RelayCommand(CanExecute = nameof(CanReadDeviceInfo))]
private Task ReadDeviceInfoAsync() => Guard(ReadDeviceInfoCoreAsync);
private async Task ReadDeviceInfoCoreAsync()
{
if (!Ready || endpoint is not { } address || activeAdb is not { } adb) return;
var current = client;
var text = await AdbAsync(adb, lifetime.Token, "-s", address, "shell",
"getprop ro.product.model; getprop ro.build.version.release; getprop ro.build.version.sdk");
if (endpoint != address || client != current) return;
var lines = text.Replace("\r", "").Split('\n');
Model = lines.ElementAtOrDefault(0)?.Trim() ?? "未知";
AndroidVersion = lines.ElementAtOrDefault(1)?.Trim() ?? "未知";
ApiLevel = lines.ElementAtOrDefault(2)?.Trim() ?? "未知";
Notice = "设备信息已更新。";
}
private Task ReadDeviceInfoAsync() => Guard(async () => { if (Current is { } c) await c.ReadInfoAsync(); });
[RelayCommand(CanExecute = nameof(CanDisconnect))]
private Task DisconnectAsync() => Guard(() => Exclusive(async () =>
{
await DisconnectCoreAsync(); Notice = "连接已释放,远程手机守护程序继续在线。";
private Task DisconnectAsync() => Guard(() => Exclusive(async () => {
var current = Current;
if (current != null) await current.DisconnectAsync();
await RefreshDevicesAsync(announce: false);
}));
private async Task ReconnectConnectionAsync(DeviceConnection connection)
{
var id = connection.DeviceId;
await connection.DisconnectAsync();
await Task.Delay(300, lifetime.Token);
await ConnectCoreAsync(new DeviceItem(id, false, false));
}
[RelayCommand(CanExecute = nameof(CanDisconnect))]
private Task ReconnectAsync() => Guard(() => Exclusive(async () =>
{
var id = activeId ?? throw new InvalidOperationException("尚未连接设备。");
await DisconnectCoreAsync();
DeviceItem? candidate = null;
for (var attempt = 0; attempt < 4; attempt++)
{
await Task.Delay(300, lifetime.Token);
await RefreshDevicesAsync(announce: false);
candidate = Devices.FirstOrDefault(d => d.Id == id);
if (candidate is { Busy: false }) break;
}
if (candidate == null) throw new InvalidOperationException("设备暂时不在线,请等待守护程序恢复后重试。");
await ConnectCoreAsync(candidate);
}));
private async Task DisconnectCoreAsync()
{
await StopScrcpyAsync();
var usb = usbSession; usbSession = null;
if (usb != null) await usb.StopAsync(Log);
var current = client; client = null;
await ProcessTools.StopAsync(current);
if (usb == null && endpoint != null && activeAdb != null)
try { await AdbAsync(activeAdb, CancellationToken.None, "disconnect", endpoint); }
catch (Exception error) { Log(error.Message); }
if (transportFile != null) { try { File.Delete(transportFile); } catch (IOException) { } }
if (leaseFile != null) { try { File.Delete(leaseFile); } catch (IOException) { } }
leaseFile = null;
transportFile = null; TransportStatus = "尚未建立数据通道";
rawEndpoint = endpoint = activeAdb = activeId = null;
HasConnection = Ready = false;
UpdateLocalOwnership();
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
Status = "已断开"; ActiveEndpoint = "本地 ADB 通道已释放";
Model = AndroidVersion = ApiLevel = "—";
}
private Task ReconnectAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await ReconnectConnectionAsync(c); }));
[RelayCommand(CanExecute = nameof(CanStartScrcpy))]
private Task StartScrcpyAsync() => Guard(async () =>
private Task StartScrcpyAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await StartScreenAsync(c); }));
private IEnumerable<int> ReservedPorts() => Connections.SelectMany(c => new int?[] { c.Options.Port, c.Options.UsbPort, c.ScreenPort }).Where(p => p.HasValue).Select(p => p!.Value);
private Task StartScreenAsync(DeviceConnection connection)
{
if (!Ready || endpoint is not { } address || activeAdb is not { } adb) return;
var current = client;
if (MaxSize is < 256 or > 8192 || MaxFps is < 1 or > 240)
throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");
var executable = DesktopPaths.ResolveTool(ScrcpyPath, "scrcpy");
var state = await AdbAsync(adb, lifetime.Token, "-s", address, "get-state");
if (state.Trim() != "device" || endpoint != address || client != current) throw new InvalidOperationException("设备尚未就绪。");
var arguments = new List<string> { "--serial", address, "--force-adb-forward", "--window-title", $"ADS · {activeId}",
"--max-size", MaxSize.ToString(), "--max-fps", MaxFps.ToString() };
if (!Audio) arguments.Add("--no-audio");
if (ViewOnly) arguments.Add("--no-control");
var info = ProcessTools.CreateStartInfo(executable, arguments);
info.Environment["ADB"] = adb;
scrcpy = Start(info); ScreenRunning = true;
Log("手机控制进程已启动:" + activeId);
Notice = "手机控制窗口已启动。";
});
[RelayCommand(CanExecute = nameof(CanStopScrcpy))]
private async Task StopScrcpyAsync()
{
var current = scrcpy; scrcpy = null;
await ProcessTools.StopAsync(current); ScreenRunning = false;
if (current != null) Log("手机控制进程已停止。");
var port = ConnectionPorts.Allocate(27183, ReservedPorts());
return connection.StartScreenAsync(ScrcpyPath, MaxSize, MaxFps, Audio, ViewOnly, port);
}
[RelayCommand(CanExecute = nameof(CanStopScrcpy))]
private Task StopScrcpyAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await c.StopScreenAsync(); }));
[RelayCommand(CanExecute = nameof(CanConnectAll))]
private Task ConnectAllAsync() => Guard(() => Exclusive(async () => {
var available = Devices.Where(d => d.Online && !d.Busy && !d.IsLocal).ToArray(); var failed = 0;
foreach (var device in available) {
try { await ConnectCoreAsync(device); } catch (Exception error) { failed++; Log($"[{device.Id}] {error.Message}"); }
}
Notice = $"已处理 {available.Length} 台设备,失败 {failed} 台。";
}));
[RelayCommand(CanExecute = nameof(CanDisconnectAll))]
private Task DisconnectAllAsync() => Guard(() => Exclusive(DisconnectAllCoreAsync));
private async Task DisconnectAllCoreAsync()
{
foreach (var connection in Connections.ToArray()) {
try { await connection.ShutdownAsync(); } catch (Exception error) { Log($"[{connection.DeviceId}] {error.Message}"); }
}
SyncSelected();
}
[RelayCommand(CanExecute = nameof(CanStartAllScreens))]
private Task StartAllScreensAsync() => Guard(() => Exclusive(async () => {
foreach (var connection in Connections.Where(c => c.Ready && !c.ScreenRunning).ToArray()) {
try { await StartScreenAsync(connection); } catch (Exception error) { Log($"[{connection.DeviceId}] {error.Message}"); }
}
}));
[RelayCommand] private void SelectConnection(DeviceConnection connection) => SelectedDevice = Devices.FirstOrDefault(d => d.Id == connection.DeviceId);
private bool CanManage(DeviceConnection? connection) => !IsWorking && connection?.HasConnection == true && Connections.Contains(connection);
[RelayCommand(CanExecute = nameof(CanManage))] private Task DisconnectDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => connection.DisconnectAsync()));
[RelayCommand(CanExecute = nameof(CanManage))] private Task ReconnectDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => ReconnectConnectionAsync(connection)));
private bool CanStartDeviceScreen(DeviceConnection? connection) => CanManage(connection) && connection!.Ready && !connection.ScreenRunning;
private bool CanStopDeviceScreen(DeviceConnection? connection) => CanManage(connection) && connection!.ScreenRunning;
[RelayCommand(CanExecute = nameof(CanStartDeviceScreen))] private Task StartScreenDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => StartScreenAsync(connection)));
[RelayCommand(CanExecute = nameof(CanStopDeviceScreen))] private Task StopScreenDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => connection.StopScreenAsync()));
[RelayCommand]
private Task CheckToolsAsync() => Guard(async () =>
@@ -554,7 +463,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
Server = Server.Trim(), Origin = Origin.Trim(), Client = ClientPath, Adb = AdbPath, Scrcpy = ScrcpyPath,
UsbMode = UsbMode, UsbipPath = UsbipPath, UsbPort = UsbPort, RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = activeId ?? SelectedDevice?.Id ?? preferredDevice
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = SelectedDevice?.Id ?? preferredDevice
});
Notice = "配置已保存;令牌内容未写入配置。";
}
@@ -577,7 +486,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
timer.Stop(); lifetime.Cancel();
await connectionGate.WaitAsync();
try { await DisconnectCoreAsync(); }
try { await DisconnectAllCoreAsync(); }
finally { connectionGate.Release(); }
}
@@ -585,11 +494,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
if (disposed) return;
disposed = true; timer.Stop(); lifetime.Cancel();
foreach (var process in new[] { scrcpy, client })
{
try { if (process != null && !process.HasExited) process.Kill(entireProcessTree: true); } catch { }
process?.Dispose();
}
foreach (var session in sessions.Values) { session.PropertyChanged -= ConnectionChanged; session.Dispose(); }
sessions.Clear(); Connections.Clear();
lifetime.Dispose();
}
}