feat: manage multiple desktop device connections independently
This commit is contained in:
1 parent
08d60de364
commit
05d4d5fea6
12 files changed
+504
-249
No files matched your search
@@ -22,7 +22,7 @@
|
||||
| `crates/` | Rust 工作区共享库容器 | Rust、TOML |
|
||||
| `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML |
|
||||
| `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown |
|
||||
| `desktop/Ads.Desktop/` | Avalonia 桌面应用,管理配置、设备列表、连接、托盘及 scrcpy 子进程;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
|
||||
| `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
|
||||
| `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) |
|
||||
| `desktop/Ads.Desktop.Smoke/` | 桌面离屏布局、连接及可选真机冒烟验证入口 | C#、XML(csproj) |
|
||||
| `deploy/` | 服务器/设备端部署脚本与 Caddy、Nginx、systemd、launchd 配置示例 | Shell、服务/代理配置、XML(plist)、Markdown |
|
||||
|
||||
@@ -29,7 +29,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
|
||||
| `crates/` | Rust 工作区共享库容器 | Rust、TOML |
|
||||
| `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML |
|
||||
| `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown |
|
||||
| `desktop/Ads.Desktop/` | Avalonia 桌面应用,管理配置、设备列表、连接、托盘及 scrcpy 子进程;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
|
||||
| `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
|
||||
| `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) |
|
||||
| `desktop/Ads.Desktop.Smoke/` | 桌面离屏布局、连接及可选真机冒烟验证入口 | C#、XML(csproj) |
|
||||
| `deploy/` | 服务器/设备端部署脚本与 Caddy、Nginx、systemd、launchd 配置示例 | Shell、服务/代理配置、XML(plist)、Markdown |
|
||||
|
||||
@@ -3,6 +3,7 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
@@ -23,7 +24,7 @@ internal static class Program
|
||||
Exception? failure = null;
|
||||
Dispatcher.UIThread.Post(async () =>
|
||||
{
|
||||
try { await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
|
||||
try { if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
|
||||
catch (Exception error) { failure = error; }
|
||||
finally { finished.Cancel(); }
|
||||
});
|
||||
@@ -39,7 +40,7 @@ internal static class Program
|
||||
|
||||
private static async Task UntilAsync(Func<bool> condition, string message)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(35);
|
||||
var deadline = DateTime.UtcNow.AddSeconds(60);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) throw new InvalidOperationException(message);
|
||||
@@ -47,6 +48,68 @@ internal static class Program
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RunMultiAsync(bool usb)
|
||||
{
|
||||
var root = DesktopPaths.ProjectRoot()!;
|
||||
var folder = Path.Combine(root, "work", "desktop-multi", Guid.NewGuid().ToString("N"));
|
||||
using var vm = new MainViewModel(folder, backgroundMonitoring: true, loadLocalCredentials: true);
|
||||
int FreePort() { var probe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); probe.Start(); var port = ((System.Net.IPEndPoint)probe.LocalEndpoint).Port; probe.Stop(); return port; }
|
||||
vm.Port = FreePort(); vm.UsbPort = FreePort(); vm.UsbMode = usb;
|
||||
var secondId = Environment.GetEnvironmentVariable("ADS_MULTI_SECOND_DEVICE") ?? "smoke-multi-phone";
|
||||
var window = new MainWindow { DataContext = vm }; window.Show();
|
||||
try {
|
||||
await vm.InitializeAsync();
|
||||
await UntilAsync(() => vm.Devices.Any(d => d.Id == "home-phone") && vm.Devices.Any(d => d.Id == secondId), "Two test devices were not discovered");
|
||||
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
|
||||
Require(!vm.SelectedDevice.Busy, "First device is occupied");
|
||||
await vm.ConnectCommand.ExecuteAsync(null);
|
||||
await UntilAsync(() => vm.Ready, "First phone was not ready: " + vm.Notice);
|
||||
var first = vm.Connections.Single(); var firstEndpoint = first.Endpoint;
|
||||
vm.SelectedDevice = vm.Devices.Single(d => d.Id == secondId);
|
||||
Require(vm.ConnectCommand.CanExecute(null), "A connected phone prevented connecting another");
|
||||
await vm.ConnectCommand.ExecuteAsync(null);
|
||||
await UntilAsync(() => vm.Connections.Count == 2 && vm.Connections.All(c => c.Ready && c.Model != "—"), "Both phones did not become ready: " + vm.Notice);
|
||||
var second = vm.Connections.Single(c => c.DeviceId == secondId);
|
||||
Require(first.Options.Port != second.Options.Port && first.Endpoint != second.Endpoint, "Device endpoints collided");
|
||||
if (usb) Require(first.Options.UsbPort != second.Options.UsbPort && first.Options.UsbPort != second.Options.Port && second.Options.UsbPort != first.Options.Port, "USB/IP ports collided");
|
||||
Require(first.Endpoint == firstEndpoint && first.HasConnection, "Selecting another phone altered the first connection");
|
||||
Require(vm.Devices.Count(d => d.IsLocal) == 2, "Local ownership was only shown for the selected phone");
|
||||
await vm.StartAllScreensCommand.ExecuteAsync(null);
|
||||
await UntilAsync(() => vm.Connections.All(c => c.ScreenRunning) && vm.Logs.Any(l => l.Contains("[home-phone]") && l.Contains("INFO: Texture")) && vm.Logs.Any(l => l.Contains("[" + secondId + "]") && l.Contains("INFO: Texture")), "Two independent scrcpy streams did not start");
|
||||
Require(first.ScreenPort != second.ScreenPort, "scrcpy forwarding ports collided");
|
||||
Require(window.FindControl<ItemsControl>("ConnectionsList")?.ItemCount == 2, "Overview did not display both connections");
|
||||
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", usb ? "desktop-multi-usb.png" : "desktop-multi.png"));
|
||||
var buttons = window.GetVisualDescendants().OfType<Button>().Where(b => b.Content as string == "查看").ToArray();
|
||||
Require(buttons.Length == 2 && buttons.All(b => b.Command != null), "Overview action bindings were not resolved");
|
||||
var selectFirst = buttons.Single(b => b.CommandParameter == first);
|
||||
selectFirst.Command!.Execute(selectFirst.CommandParameter);
|
||||
Require(vm.Current == first && vm.Endpoint == firstEndpoint, "Overview did not select the requested device");
|
||||
Console.WriteLine("PASS: two " + (usb ? "USB" : "network") + " connections, distinct ports/serials, overview actions, two real scrcpy video streams");
|
||||
await vm.ReconnectDeviceCommand.ExecuteAsync(first);
|
||||
await UntilAsync(() => vm.Connections.Count == 2 && vm.Connections.All(c => c.Ready), "Reconnecting first phone did not recover it");
|
||||
Require(second.HasConnection && second.Ready && second.ScreenRunning, "Reconnecting one phone interrupted the other");
|
||||
first = vm.Connections.Single(c => c.DeviceId == "home-phone");
|
||||
if (usb) {
|
||||
vm.SelectConnectionCommand.Execute(first);
|
||||
await vm.ClearPortCommand.ExecuteAsync(null);
|
||||
} else await vm.DisconnectDeviceCommand.ExecuteAsync(first);
|
||||
await UntilAsync(() => vm.Connections.Count == 1, "Disconnect did not remove only the first phone");
|
||||
Require(second.HasConnection && second.Ready && second.ScreenRunning, "Disconnecting one phone interrupted the other");
|
||||
vm.SelectedDevice = vm.Devices.Single(d => d.Id == secondId);
|
||||
await vm.ReadDeviceInfoCommand.ExecuteAsync(null);
|
||||
Require(vm.Model != "—", "Second phone stopped responding after first disconnected");
|
||||
Console.WriteLine("PASS: disconnecting one phone preserves the other's ADB and video");
|
||||
await vm.DisconnectAllCommand.ExecuteAsync(null);
|
||||
Require(vm.Connections.Count == 0 && !vm.HasConnections, "Disconnect all leaked a connection");
|
||||
await vm.RefreshCommand.ExecuteAsync(null);
|
||||
Require(vm.Devices.Where(d => d.Id == "home-phone" || d.Id == secondId).All(d => !d.Busy), "Multi-device leases were not released");
|
||||
Require(!vm.Logs.Any(l => l.Contains(vm.Token)), "A multi-device log leaked a token");
|
||||
Console.WriteLine("PASS: selected reconnect, disconnect all and independent lease cleanup");
|
||||
} finally {
|
||||
await vm.ShutdownAsync(); File.WriteAllLines(Path.Combine(root, "work", "desktop-multi.log"), vm.Logs); window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RunAsync(bool live, bool screen, bool usb)
|
||||
{
|
||||
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
|
||||
@@ -83,8 +146,9 @@ internal static class Program
|
||||
try
|
||||
{
|
||||
vm.Port = ((System.Net.IPEndPoint)occupied.LocalEndpoint).Port;
|
||||
await vm.ConnectCommand.ExecuteAsync(null);
|
||||
Require(!vm.HasConnection && vm.Notice.Contains("已被占用"), "Occupied port was not rejected safely");
|
||||
var allocated = ConnectionPorts.Allocate(vm.Port, []);
|
||||
Require(allocated != vm.Port, "Automatic allocation did not skip occupied port");
|
||||
Require(!vm.HasConnection, "Port check started an unwanted connection");
|
||||
}
|
||||
finally { occupied.Stop(); }
|
||||
var childInfo = ProcessTools.CreateStartInfo("dotnet", [typeof(Program).Assembly.Location, "--port-child", vm.Port.ToString()]);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Ads.Desktop;
|
||||
using Xunit;
|
||||
namespace Ads.Desktop.Tests;
|
||||
public class ConnectionPortsTests
|
||||
{
|
||||
[Fact] public void AllocationSkipsReservedAndForeignListenerWithoutClosingIt()
|
||||
{
|
||||
var occupied = new TcpListener(IPAddress.Loopback, 0); occupied.Start();
|
||||
try {
|
||||
var first = ((IPEndPoint)occupied.LocalEndpoint).Port;
|
||||
var a = ConnectionPorts.Allocate(first, [first + 1]);
|
||||
var b = ConnectionPorts.Allocate(first, [first + 1, a]);
|
||||
Assert.NotEqual(first, a); Assert.NotEqual(first + 1, a); Assert.NotEqual(a, b);
|
||||
Assert.True(occupied.Server.IsBound);
|
||||
} finally { occupied.Stop(); }
|
||||
}
|
||||
[Fact] public void AdbServerPortIsNeverAllocated() => Assert.NotEqual(5037, ConnectionPorts.Allocate(5037, []));
|
||||
[Fact] public void ExhaustedRangeFailsWithoutReusingReservedPort() => Assert.Throws<InvalidOperationException>(() => ConnectionPorts.Allocate(65535, [65535]));
|
||||
[Theory] [InlineData(0)] [InlineData(65536)]
|
||||
public void InvalidBasePortFails(int port) => Assert.Throws<InvalidOperationException>(() => ConnectionPorts.Allocate(port, []));
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public partial class App : Application
|
||||
}
|
||||
var menu = new NativeMenu();
|
||||
var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
|
||||
menu.Items.Add(new NativeMenuItem("断开当前连接") { Command = vm.DisconnectCommand });
|
||||
menu.Items.Add(new NativeMenuItem("断开全部设备") { Command = vm.DisconnectAllCommand });
|
||||
menu.Items.Add(new NativeMenuItemSeparator());
|
||||
var quit = new NativeMenuItem("退出并断开连接");
|
||||
quit.Click += async (_, _) => await QuitAsync();
|
||||
@@ -36,8 +36,8 @@ public partial class App : Application
|
||||
var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
|
||||
TrayIcon.SetIcons(this, new TrayIcons { tray });
|
||||
vm.PropertyChanged += (_, change) => {
|
||||
if (change.PropertyName is nameof(vm.Status) or nameof(vm.ActiveDeviceId))
|
||||
tray.ToolTipText = "ADS · " + vm.Status;
|
||||
if (change.PropertyName is nameof(vm.ConnectionSummary))
|
||||
tray.ToolTipText = "ADS · " + vm.ConnectionSummary;
|
||||
};
|
||||
window.Closing += async (_, e) => {
|
||||
if (quitting) return;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
namespace Ads.Desktop;
|
||||
|
||||
public static class ConnectionPorts
|
||||
{
|
||||
/// <summary>Find a free loopback port without terminating another application's listener.</summary>
|
||||
public static int Allocate(int first, IEnumerable<int> reserved)
|
||||
{
|
||||
if (first is < 1024 or > 65535) throw new InvalidOperationException("起始端口范围为 1024–65535。");
|
||||
var excluded = reserved.ToHashSet(); excluded.Add(5037);
|
||||
for (var port = first; port <= 65535; port++) {
|
||||
if (excluded.Contains(port)) continue;
|
||||
var probe = new TcpListener(IPAddress.Loopback, port);
|
||||
try { probe.Server.ExclusiveAddressUse = true; probe.Start(); return port; }
|
||||
catch (SocketException) { }
|
||||
finally { probe.Stop(); }
|
||||
}
|
||||
throw new InvalidOperationException("没有可用的本地端口,请修改起始端口或释放其他连接。");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace Ads.Desktop;
|
||||
|
||||
public sealed record ConnectionOptions(RelayOptions Relay, string Client, string Adb, bool UsbMode,
|
||||
string Usbip, bool RelayOnly, int Port, int? UsbPort, string Folder);
|
||||
|
||||
/// <summary>One phone owns its processes, USB export, status files and operation lock.</summary>
|
||||
public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
{
|
||||
public string DeviceId { get; }
|
||||
public ConnectionOptions Options { get; }
|
||||
public string Mode => Options.UsbMode ? "USB ADB" : "网络 ADB";
|
||||
public string PortSummary => $"隧道 {Options.Port}" + (Options.UsbPort is { } u ? $" · USB/IP {u}" : "") + (ScreenPort is { } p ? $" · 投屏 {p}" : "");
|
||||
public string RawEndpoint => $"127.0.0.1:{Options.Port}";
|
||||
[ObservableProperty] private string? endpoint;
|
||||
[ObservableProperty] private bool hasConnection;
|
||||
[ObservableProperty] private bool ready;
|
||||
[ObservableProperty] private bool screenRunning;
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(PortSummary))] private int? screenPort;
|
||||
[ObservableProperty] private bool busy;
|
||||
[ObservableProperty] private string status = "尚未连接";
|
||||
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
|
||||
[ObservableProperty] private string model = "—";
|
||||
[ObservableProperty] private string androidVersion = "—";
|
||||
[ObservableProperty] private string apiLevel = "—";
|
||||
[ObservableProperty] private string notice = "";
|
||||
private Process? client, scrcpy;
|
||||
private WindowsUsbSession? usb;
|
||||
private string? transportFile, leaseFile;
|
||||
private readonly Action<string> log;
|
||||
private readonly SemaphoreSlim gate = new(1, 1);
|
||||
private readonly CancellationTokenSource lifetime;
|
||||
private bool disposed;
|
||||
|
||||
public DeviceConnection(string id, ConnectionOptions options, Action<string> logger, CancellationToken cancellation)
|
||||
{
|
||||
DeviceId = id; Options = options;
|
||||
log = message => logger($"[{id}] {message}");
|
||||
lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
||||
}
|
||||
private async Task Exclusive(Func<Task> action)
|
||||
{
|
||||
await gate.WaitAsync(lifetime.Token); Busy = true;
|
||||
try { await action(); }
|
||||
finally { Busy = false; gate.Release(); }
|
||||
}
|
||||
public Task ConnectAsync() => Exclusive(async () =>
|
||||
{
|
||||
if (HasConnection) throw new InvalidOperationException("该设备已经连接。");
|
||||
try {
|
||||
var info = ProcessTools.ClientStartInfo(Options.Client, Options.Adb, Options.Relay, DeviceId, RawEndpoint);
|
||||
Directory.CreateDirectory(Options.Folder);
|
||||
transportFile = Path.Combine(Options.Folder, "transport-" + Guid.NewGuid().ToString("N") + ".json");
|
||||
info.ArgumentList.Add("--transport"); info.ArgumentList.Add(Options.RelayOnly ? "relay" : "auto");
|
||||
info.ArgumentList.Add("--status-file"); info.ArgumentList.Add(transportFile);
|
||||
if (Options.UsbMode) {
|
||||
leaseFile = Path.Combine(Options.Folder, "lease-" + Guid.NewGuid().ToString("N") + ".json");
|
||||
info.ArgumentList.Add("--no-auto-connect");
|
||||
info.ArgumentList.Add("--lease-status-file"); info.ArgumentList.Add(leaseFile);
|
||||
}
|
||||
client = Start(info); Endpoint = RawEndpoint;
|
||||
HasConnection = true; Ready = false; Status = "正在连接 · 等待设备就绪";
|
||||
TransportStatus = "正在协商连接路线";
|
||||
Model = AndroidVersion = ApiLevel = "—";
|
||||
log($"连接已启动,隧道 {RawEndpoint}。");
|
||||
if (Options.UsbMode) {
|
||||
usb = new WindowsUsbSession(DeviceId);
|
||||
await usb.StartAsync(Options.Usbip, Options.UsbPort!.Value, RawEndpoint, leaseFile!, log, lifetime.Token);
|
||||
Endpoint = usb.Serial;
|
||||
}
|
||||
Notice = "连接已启动;首次使用时请在手机上允许调试。";
|
||||
} catch { await DisconnectCoreAsync(); throw; }
|
||||
});
|
||||
private Process Start(ProcessStartInfo info)
|
||||
{
|
||||
var process = new Process { StartInfo = info };
|
||||
process.OutputDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
|
||||
process.ErrorDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
|
||||
try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); return process; }
|
||||
catch { process.Dispose(); throw; }
|
||||
}
|
||||
private async Task<string> AdbAsync(params string[] arguments)
|
||||
{
|
||||
var result = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(Options.Adb, arguments), lifetime.Token);
|
||||
if (result.ExitCode != 0) throw new InvalidOperationException("ADB:" + result.Error.Trim());
|
||||
return result.Output;
|
||||
}
|
||||
public async Task MonitorAsync(string listing)
|
||||
{
|
||||
if (disposed || !HasConnection || !await gate.WaitAsync(0)) return;
|
||||
try {
|
||||
if (scrcpy is { HasExited: true }) {
|
||||
log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
|
||||
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false; ScreenPort = null;
|
||||
}
|
||||
if (client is { HasExited: true } || usb is { HasExited: true }) {
|
||||
var reason = client is { HasExited: true } ? $"连接程序退出,代码 {client.ExitCode}" : "USB 模拟进程退出";
|
||||
await DisconnectCoreAsync(); Status = reason; Notice = reason + ",可重新连接。"; log(Notice); return;
|
||||
}
|
||||
if (transportFile != null && File.Exists(transportFile)) {
|
||||
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) { }
|
||||
}
|
||||
var row = listing.Split('\n').Select(l => l.Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))
|
||||
.FirstOrDefault(parts => parts.Length >= 2 && parts[0] == Endpoint);
|
||||
var wasReady = Ready; Ready = row?[1] == "device";
|
||||
Status = row?[1] switch {
|
||||
"device" => "已连接 · 可调试和控制", "unauthorized" => "等待手机允许此电脑调试",
|
||||
"offline" => "设备离线 · 正在恢复连接", _ => "正在恢复连接 · 等待设备或网络"
|
||||
};
|
||||
if (Ready && !wasReady) { log("设备已就绪。"); await ReadInfoCoreAsync(); }
|
||||
} catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||||
catch (Exception error) { Ready = false; Notice = error.Message; log(error.Message); }
|
||||
finally { gate.Release(); }
|
||||
}
|
||||
public void MonitoringFailed(string message) { Ready = false; Status = "ADB 检测失败"; Notice = message; }
|
||||
public Task ReadInfoAsync() => Exclusive(ReadInfoCoreAsync);
|
||||
private async Task ReadInfoCoreAsync()
|
||||
{
|
||||
if (!Ready || Endpoint == null) return;
|
||||
var text = await AdbAsync("-s", Endpoint, "shell", "getprop ro.product.model; getprop ro.build.version.release; getprop ro.build.version.sdk");
|
||||
var lines = text.Replace("\r", "").Split('\n');
|
||||
Model = lines.ElementAtOrDefault(0)?.Trim() ?? "未知";
|
||||
AndroidVersion = lines.ElementAtOrDefault(1)?.Trim() ?? "未知";
|
||||
ApiLevel = lines.ElementAtOrDefault(2)?.Trim() ?? "未知";
|
||||
Notice = "设备信息已更新。";
|
||||
}
|
||||
public Task StartScreenAsync(string path, int size, int fps, bool audio, bool viewOnly, int port) => Exclusive(async () =>
|
||||
{
|
||||
if (!Ready || Endpoint == null || ScreenRunning) return;
|
||||
if (size is < 256 or > 8192 || fps is < 1 or > 240) throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");
|
||||
var executable = DesktopPaths.ResolveTool(path, "scrcpy");
|
||||
if ((await AdbAsync("-s", Endpoint, "get-state")).Trim() != "device") throw new InvalidOperationException("设备尚未就绪。");
|
||||
var args = new List<string> { "--serial", Endpoint, "--force-adb-forward", "--window-title", $"ADS · {DeviceId}", "--max-size", size.ToString(), "--max-fps", fps.ToString(), "--port", port.ToString() };
|
||||
if (!audio) args.Add("--no-audio"); if (viewOnly) args.Add("--no-control");
|
||||
var info = ProcessTools.CreateStartInfo(executable, args); info.Environment["ADB"] = Options.Adb;
|
||||
scrcpy = Start(info); ScreenPort = port; ScreenRunning = true; Notice = "手机控制窗口已启动。"; log(Notice);
|
||||
});
|
||||
public Task StopScreenAsync() => Exclusive(StopScreenCoreAsync);
|
||||
private async Task StopScreenCoreAsync()
|
||||
{
|
||||
var current = scrcpy; scrcpy = null;
|
||||
try { await ProcessTools.StopAsync(current); }
|
||||
finally { ScreenRunning = false; ScreenPort = null; }
|
||||
}
|
||||
public Task DisconnectAsync() => Exclusive(DisconnectCoreAsync);
|
||||
// Shutdown must also work after the shared cancellation token has been cancelled.
|
||||
public async Task ShutdownAsync()
|
||||
{
|
||||
await gate.WaitAsync();
|
||||
try { await DisconnectCoreAsync(); }
|
||||
finally { gate.Release(); }
|
||||
}
|
||||
private async Task DisconnectCoreAsync()
|
||||
{
|
||||
try { await StopScreenCoreAsync(); } catch (Exception e) { log(e.Message); }
|
||||
var currentUsb = usb; usb = null;
|
||||
if (currentUsb != null) { try { await currentUsb.StopAsync(log); } catch (Exception e) { log(e.Message); } }
|
||||
var current = client; client = null;
|
||||
try { await ProcessTools.StopAsync(current); } catch (Exception e) { log(e.Message); }
|
||||
if (currentUsb == null && Endpoint != null) {
|
||||
try { await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(Options.Adb, ["disconnect", Endpoint])); }
|
||||
catch (Exception e) { log(e.Message); }
|
||||
}
|
||||
foreach (var file in new[] { transportFile, leaseFile }) {
|
||||
if (file != null) try { File.Delete(file); } catch (IOException e) { log(e.Message); }
|
||||
}
|
||||
transportFile = leaseFile = null;
|
||||
Endpoint = null; HasConnection = Ready = false;
|
||||
Status = "已断开"; TransportStatus = "尚未建立数据通道";
|
||||
Model = AndroidVersion = ApiLevel = "—";
|
||||
Notice = "连接已释放,远程守护程序继续在线。";
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed) return; disposed = true; lifetime.Cancel();
|
||||
usb?.Dispose(); usb = null;
|
||||
foreach (var p in new[] { scrcpy, client }) {
|
||||
try { if (p != null && !p.HasExited) p.Kill(entireProcessTree: true); } catch { }
|
||||
p?.Dispose();
|
||||
}
|
||||
scrcpy = client = null; lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -24,20 +24,48 @@
|
||||
<TabItem Header="设备与连接">
|
||||
<Grid ColumnDefinitions="320,*" Margin="0,16,0,0">
|
||||
<Border Classes="card" Margin="0,0,16,0">
|
||||
<Grid RowDefinitions="Auto,*,Auto,Auto">
|
||||
<Grid RowDefinitions="Auto,*,Auto,Auto,Auto">
|
||||
<TextBlock Text="在线设备" Classes="section"/>
|
||||
<ListBox x:Name="DeviceList" Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice}" Margin="0,14,0,12" Background="Transparent">
|
||||
<ListBox.ItemTemplate><DataTemplate><StackPanel Margin="5,10" Spacing="6"><TextBlock Text="{Binding Id}" FontSize="17" TextWrapping="Wrap"/><TextBlock Text="{Binding Description}" Classes="label" TextWrapping="Wrap"/></StackPanel></DataTemplate></ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Grid.Row="2" Text="{Binding DeviceSummary}" Classes="label" TextWrapping="Wrap"/>
|
||||
<CheckBox Grid.Row="3" Content="自动刷新设备列表" IsChecked="{Binding AutoRefresh}" Margin="0,12,0,0"/>
|
||||
<TextBlock Grid.Row="2" Text="{Binding ConnectionSummary}" Foreground="#66D9C0" Margin="0,0,0,8" TextWrapping="Wrap"/>
|
||||
<TextBlock Grid.Row="3" Text="{Binding DeviceSummary}" Classes="label" TextWrapping="Wrap"/>
|
||||
<CheckBox Grid.Row="4" Content="自动刷新设备列表" IsChecked="{Binding AutoRefresh}" Margin="0,12,0,0"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<ScrollViewer Grid.Column="1">
|
||||
<StackPanel Spacing="14">
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Text="连接管理" Classes="section"/>
|
||||
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="多设备连接总览" Classes="section"/><TextBlock Grid.Column="1" Text="{Binding ConnectionSummary}" Foreground="#66D9C0" VerticalAlignment="Center"/></Grid>
|
||||
<WrapPanel><Button x:Name="ConnectAllButton" Content="连接全部空闲设备" Command="{Binding ConnectAllCommand}"/><Button Content="投屏全部就绪设备" Command="{Binding StartAllScreensCommand}"/><Button x:Name="DisconnectAllButton" Content="断开全部" Command="{Binding DisconnectAllCommand}"/></WrapPanel>
|
||||
<ScrollViewer MaxHeight="380">
|
||||
<ItemsControl x:Name="ConnectionsList" ItemsSource="{Binding Connections}">
|
||||
<ItemsControl.ItemTemplate><DataTemplate>
|
||||
<Border Background="#101923" CornerRadius="8" Padding="12" Margin="0,0,0,8">
|
||||
<StackPanel Spacing="6">
|
||||
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="{Binding DeviceId}" FontSize="17" FontWeight="SemiBold"/><TextBlock Grid.Column="1" Text="{Binding Mode}" Foreground="#66D9C0"/></Grid>
|
||||
<TextBlock Text="{Binding Status}" Foreground="#66D9C0"/>
|
||||
<TextBlock Text="{Binding Endpoint}" Classes="label"/><TextBlock Text="{Binding PortSummary}" Classes="label" FontSize="12" TextWrapping="Wrap"/><TextBlock Text="{Binding TransportStatus}" Classes="label" TextWrapping="Wrap"/>
|
||||
<WrapPanel>
|
||||
<Button Content="查看" Command="{Binding $parent[Window].DataContext.SelectConnectionCommand}" CommandParameter="{Binding}" Padding="10,6"/>
|
||||
<Button Content="打开控制" Command="{Binding $parent[Window].DataContext.StartScreenDeviceCommand}" CommandParameter="{Binding}" IsEnabled="{Binding Ready}" Padding="10,6"/>
|
||||
<Button Content="停止投屏" Command="{Binding $parent[Window].DataContext.StopScreenDeviceCommand}" CommandParameter="{Binding}" IsEnabled="{Binding ScreenRunning}" Padding="10,6"/>
|
||||
<Button Content="重连" Command="{Binding $parent[Window].DataContext.ReconnectDeviceCommand}" CommandParameter="{Binding}" Padding="10,6"/>
|
||||
<Button Content="断开" Command="{Binding $parent[Window].DataContext.DisconnectDeviceCommand}" CommandParameter="{Binding}" Padding="10,6"/>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate></ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
<TextBlock Text="端口自动分配;每台手机可打开独立控制窗口。切换左侧设备不会断开其他连接。" Classes="label" TextWrapping="Wrap" FontSize="12"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Text="所选设备 · 连接管理" Classes="section"/>
|
||||
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
|
||||
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="#A8B7CC" TextWrapping="Wrap"/>
|
||||
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
|
||||
@@ -100,14 +128,14 @@
|
||||
<CheckBox x:Name="UsbModeCheck" Content="将远程手机挂载为本机 USB ADB 设备" IsChecked="{Binding UsbMode}"/>
|
||||
<TextBlock Text="需要安装 USBip 虚拟控制器驱动。仅模拟 ADB 接口;首次使用仍需手机授权,修改在下次连接生效。" Classes="label" TextWrapping="Wrap"/>
|
||||
<TextBlock Text="usbip.exe 路径"/><TextBox Text="{Binding UsbipPath}" Watermark="C:\Program Files\USBip\usbip.exe"/>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="本机 USB/IP 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding UsbPort}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="起始 USB/IP 端口(自动分配)" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding UsbPort}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<TextBlock Text="驱动安装方式见项目 docs/windows-usb.md;默认网络 ADB 模式不需要此组件。" Classes="label" TextWrapping="Wrap"/>
|
||||
</StackPanel></Border>
|
||||
<Border Classes="card"><StackPanel Spacing="12">
|
||||
<TextBlock Text="本地连接" Classes="section"/>
|
||||
<CheckBox x:Name="RelayOnlyCheck" Content="仅使用中继(关闭时 P2P 优先,失败自动选择中继节点)" IsChecked="{Binding RelayOnly}"/>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="结束当前所选端口的监听进程"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="起始 ADB 端口(自动分配)" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="清理所选设备的隧道端口;未连接时清理起始端口"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
|
||||
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
|
||||
<TextBlock Text="配置修改在下一次连接生效。完全退出工作台会停止本机连接;远程守护程序继续运行。" TextWrapping="Wrap" Classes="label"/>
|
||||
<Button Content="保存配置" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>
|
||||
|
||||
@@ -6,7 +6,7 @@ using Microsoft.Win32;
|
||||
namespace Ads.Desktop;
|
||||
|
||||
/// <summary>Owns one loopback USB/IP export and its exact imported hub port.</summary>
|
||||
public sealed class WindowsUsbSession
|
||||
public sealed class WindowsUsbSession : IDisposable
|
||||
{
|
||||
private Process? bridge;
|
||||
private string? usbip;
|
||||
@@ -59,6 +59,12 @@ public sealed class WindowsUsbSession
|
||||
hubPort = importedPort;
|
||||
log($"USB ADB 已挂载:{Serial},本机控制器端口 {hubPort}。");
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
var current = bridge; bridge = null;
|
||||
try { if (current != null && !current.HasExited) current.Kill(entireProcessTree: true); } catch { }
|
||||
current?.Dispose(); hubPort = null;
|
||||
}
|
||||
public async Task StopAsync(Action<string> log)
|
||||
{
|
||||
// Closing our export first forces the driver to remove this device even if detach fails.
|
||||
|
||||
@@ -62,3 +62,13 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen
|
||||
## Windows USB 模拟
|
||||
|
||||
连接配置提供可选 USB 模式、usbip.exe 路径和回环 USB/IP 端口;需要已签名的 USBip UDE 控制器。启动时等待设备租约,再导入虚拟设备;监控、设备信息和 scrcpy 使用 USB 序列号。安装与限制见 [Windows USB 文档](../docs/windows-usb.md)。
|
||||
|
||||
## 同时管理多台手机
|
||||
|
||||
工作台支持同时连接多台设备。左侧切换仅改变当前详情;右侧总览保留所有连接、实际 P2P/中继路线、网络/USB 模式及标识,并提供各自的查看、控制、重连和断开。可以连接全部空闲设备、投屏全部就绪设备、断开全部;托盘与退出操作管理全部连接。
|
||||
|
||||
ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和外部进程占用。配置页端口是起始值;已连接设备保留启动时的配置,之后可改变 USB 开关,为下一台选择另一种模式。多个投屏为独立控制窗口。
|
||||
|
||||
实现分工:MainViewModel 管理设备发现、连接集合、当前选择与批量操作;DeviceConnection 为每台设备持有进程、独立操作锁、USB 导出、状态文件和生命周期;ConnectionPorts 负责不终止外部监听者的端口分配。监控每个 ADB 可执行文件每轮仅查询一次 devices,再分别更新所有设备。
|
||||
|
||||
验证:`dotnet run --project Ads.Desktop.Smoke -c Debug -- --multi`,USB 模式加 `--usb`。需要 home-phone 与 smoke-multi-phone(可用 ADS_MULTI_SECOND_DEVICE 指定第二个已授权设备 ID),测试不会接管已占用设备。2026-11-12 使用两个独立设备别名映射到同一台测试手机,验证双 ADB/双 USB、不同端口/序列号、两个真实 scrcpy 视频、总览按钮绑定、重连/断开一个保留另一个以及释放全部租约。此验证覆盖并发通道,未作为多台物理手机的大规模负载测试。
|
||||
+3
-1
@@ -44,7 +44,7 @@ ads-client → P2P / WSS 中继 → ads-agent → 手机 TCP adbd
|
||||
1. 构建后端和工作台(scripts/build.ps1、scripts/build-desktop.ps1)。
|
||||
2. 进入“连接配置 → 可选 USB 模拟 · Windows”。勾选 USB 模拟,指定 usbip.exe(默认 C:\Program Files\USBip\usbip.exe)。
|
||||
3. USB/IP 端口默认 3240,仅回环,必须与本地 ADB 隧道端口不同且未占用。
|
||||
4. 连接设备。工作台先启动 ads-client 并等待设备租约,再启动虚拟设备并调用 usbip 挂载。
|
||||
4. 连接设备。桌面支持同时挂载多台设备,每台自动分配独立 ADB、USB/IP 与投屏端口;工作台先启动 ads-client 并等待设备租约,再启动虚拟设备并调用 usbip 挂载。
|
||||
5. 本机 ADB 显示 ADS-home-phone,使用 `adb -s ADS-home-phone shell` 或桌面投屏。无需 adb connect。
|
||||
6. 断开连接时关闭本次虚拟设备和本次网络客户端,释放远端租约,不卸载控制器驱动,不操作其他 USB 设备。
|
||||
|
||||
@@ -68,3 +68,5 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen --usb
|
||||
参考:[USB/IP 协议](https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html)、[Microsoft UDE](https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/developing-windows-drivers-for-emulated-usb-host-controllers-and-devices)、[AOSP Windows USB transport](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/client/usb_windows.cpp)。
|
||||
|
||||
桌面 USB 模式实测通过:P2P 路线状态、USB 序列号选择、设备型号、真实 scrcpy 视频、重新连接、断开后释放租约、清理本机隧道端口时一并移除虚拟 USB,以及凭据不写入配置/日志。结束后 USBip 控制器导入数量为 0,物理 USB 手机保持在线。
|
||||
|
||||
多设备工作台中,切换当前设备不会断开其他 USB 设备;清理所选设备的隧道端口只释放该设备。退出和“断开全部”释放本工作台的全部虚拟 USB 设备,不卸载驱动或操作物理 USB 手机。
|
||||
Reference in new issue
Block a user