feat: add optional Windows virtual USB ADB device

This commit is contained in:
tongtong committed 2026-11-12 17:34:23 +08:00
1 parent 2abfb63da9
commit 08d60de364
23 files changed
+802 -26

No files matched your search

+8 -2
View File
@@ -23,7 +23,7 @@ internal static class Program
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { await RunAsync(args.Contains("--live"), args.Contains("--screen")); }
try { await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
@@ -47,7 +47,7 @@ internal static class Program
}
}
private static async Task RunAsync(bool live, bool screen)
private static async Task RunAsync(bool live, bool screen, bool usb)
{
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
var folder = Path.Combine(root, "work", "desktop-smoke", Guid.NewGuid().ToString("N"));
@@ -55,6 +55,11 @@ internal static class Program
// Avoid collisions with the interactive application or another local ADB device.
var temporary = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
temporary.Start(); vm.Port = ((System.Net.IPEndPoint)temporary.LocalEndpoint).Port; temporary.Stop();
vm.UsbMode = usb;
if (usb) {
var usbProbe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
usbProbe.Start(); vm.UsbPort = ((System.Net.IPEndPoint)usbProbe.LocalEndpoint).Port; usbProbe.Stop();
}
var window = new MainWindow { DataContext = vm };
window.Show();
await Task.Delay(60);
@@ -105,6 +110,7 @@ internal static class Program
await UntilAsync(() => vm.Ready && vm.Model != "—", "Device did not become ready: " + vm.Notice);
await UntilAsync(() => vm.TransportStatus.Contains("P2P") || vm.TransportStatus.Contains("中继连接"), "Transport status was not updated");
Require(window.FindControl<TextBlock>("TransportStatusText")?.Text == vm.TransportStatus, "Actual route binding failed");
if (usb) Require(vm.Endpoint?.StartsWith("ADS-") == true, "USB mode did not select the USB serial");
Console.WriteLine("PASS: two healthy nodes and actual transport shown: " + vm.TransportStatus);
Require(window.FindControl<TextBlock>("ModelText")?.Text == vm.Model, "Model UI binding failed");
Require(window.FindControl<Button>("ReconnectButton")?.IsEffectivelyEnabled == true, "Reconnect button not enabled");
@@ -13,6 +13,9 @@ public sealed class DesktopSettings
public int Port { get; set; } = 15555;
public int Size { get; set; } = 1920;
public int Fps { get; set; } = 60;
public bool UsbMode { get; set; }
public string UsbipPath { get; set; } = "";
public int UsbPort { get; set; } = 3240;
public bool RelayOnly { get; set; }
public bool Audio { get; set; }
public bool ViewOnly { get; set; }
+42 -9
View File
@@ -24,6 +24,9 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private int port = 15555;
[ObservableProperty] private int maxSize = 1920;
[ObservableProperty] private int maxFps = 60;
[ObservableProperty] private bool usbMode;
[ObservableProperty] private string usbipPath = WindowsUsbSession.DefaultUsbipPath();
[ObservableProperty] private int usbPort = 3240;
[ObservableProperty] private bool relayOnly;
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
[ObservableProperty] private bool audio;
@@ -55,8 +58,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
public string? Endpoint => endpoint;
public string? ActiveDeviceId => activeId;
private WindowsUsbSession? usbSession;
private string? leaseFile;
private Process? client, scrcpy;
private string? endpoint, activeAdb, activeId, transportFile;
private string? endpoint, rawEndpoint, activeAdb, activeId, transportFile;
private string credentialFile = "", preferredDevice = "home-phone";
private bool monitoring, disposed, initialized;
private DateTime lastRefresh;
@@ -81,6 +86,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (settings.Adb.Length > 0) AdbPath = settings.Adb;
if (settings.Scrcpy.Length > 0) ScrcpyPath = settings.Scrcpy;
Port = settings.Port; MaxSize = settings.Size; MaxFps = settings.Fps;
UsbMode = settings.UsbMode; UsbPort = settings.UsbPort;
if (settings.UsbipPath.Length > 0) UsbipPath = settings.UsbipPath;
RelayOnly = settings.RelayOnly; Audio = settings.Audio; ViewOnly = settings.ViewOnly;
MinimizeToTray = settings.Tray; AutoRefresh = settings.AutoRefresh;
credentialFile = settings.CredentialFile;
@@ -224,7 +231,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
var selectedPort = Port;
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
var releasedOwnConnection = HasConnection && endpoint == $"127.0.0.1:{selectedPort}";
var releasedOwnConnection = HasConnection && rawEndpoint == $"127.0.0.1:{selectedPort}";
var releasedUsb = releasedOwnConnection && usbSession != null;
if (releasedOwnConnection)
{
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
@@ -238,7 +246,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
try
{
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
if (!releasedUsb) await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
}
catch (Exception error) { Log("清除 ADB 端点:" + error.Message); }
PortCleanupStatus = releasedOwnConnection && ended == 0
@@ -265,7 +273,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
await ConnectCoreAsync(selected);
}));
private Task ConnectCoreAsync(DeviceItem device)
private async Task ConnectCoreAsync(DeviceItem device)
{
if (client != null) throw new InvalidOperationException("请先断开当前连接。");
if (device.Busy) throw new InvalidOperationException("设备已被其他客户端占用。");
@@ -281,6 +289,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
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 adb = DesktopPaths.ResolveTool(AdbPath, "adb");
@@ -290,9 +302,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
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);
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);
endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
rawEndpoint = address; endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
HasConnection = true; Ready = false;
UpdateLocalOwnership();
@@ -301,7 +318,15 @@ public partial class MainViewModel : ObservableObject, IDisposable
Notice = "连接已启动;首次使用时请在手机上允许调试。";
Model = AndroidVersion = ApiLevel = "—";
Log($"连接 {device.Id},本地 ADB 地址 {address}。");
return Task.CompletedTask;
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; }
}
}
private void UpdateLocalOwnership()
@@ -358,6 +383,10 @@ public partial class MainViewModel : ObservableObject, IDisposable
};
} catch (IOException) { } catch (JsonException) { }
}
if (usbSession is { HasExited: true }) {
await Exclusive(DisconnectCoreAsync);
Notice = "USB 模拟进程已退出,请查看日志后重连。";
}
var current = client;
if (current != null)
{
@@ -445,14 +474,18 @@ public partial class MainViewModel : ObservableObject, IDisposable
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 (endpoint != null && activeAdb != null)
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 = "尚未建立数据通道";
endpoint = activeAdb = activeId = null;
rawEndpoint = endpoint = activeAdb = activeId = null;
HasConnection = Ready = false;
UpdateLocalOwnership();
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
@@ -520,7 +553,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
DesktopPaths.SaveSettings(settingsFile, new DesktopSettings
{
Server = Server.Trim(), Origin = Origin.Trim(), Client = ClientPath, Adb = AdbPath, Scrcpy = ScrcpyPath,
RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
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
});
Notice = "配置已保存;令牌内容未写入配置。";
+9 -1
View File
@@ -41,7 +41,7 @@
<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"/>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制设备标识" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
</StackPanel>
</Border>
@@ -95,6 +95,14 @@
<TextBlock Text="scrcpy 可执行文件"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ScrcpyPath}"/><Button Grid.Column="1" Content="选择" Tag="scrcpy" Click="ChooseToolClick" Margin="10,5,0,12"/></Grid>
<TextBlock Text="{Binding ToolsStatus}" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="10">
<TextBlock Text="可选 USB 模拟 · Windows" Classes="section"/>
<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>
<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}"/>
+72
View File
@@ -0,0 +1,72 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
namespace Ads.Desktop;
/// <summary>Owns one loopback USB/IP export and its exact imported hub port.</summary>
public sealed class WindowsUsbSession
{
private Process? bridge;
private string? usbip;
private int? hubPort;
public string Serial { get; }
public bool HasExited => bridge is { HasExited: true };
public WindowsUsbSession(string device) => Serial = "ADS-" + (device.Length <= 116 ? device : Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(device)))[..24]);
public static string DefaultUsbipPath()
{
var candidate = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "USBip", "usbip.exe");
return File.Exists(candidate) ? candidate : "usbip";
}
public static void Validate(string path, int port)
{
if (!OperatingSystem.IsWindows()) throw new InvalidOperationException("USB 模拟目前仅支持 Windows。");
if (port is < 1024 or > 65535) throw new InvalidOperationException("USB/IP 端口范围为 1024–65535。");
using var service = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\usbip2_ude");
if (service == null) throw new InvalidOperationException("未安装 USBip 虚拟控制器驱动,请先使用 USB 模拟配置中的安装说明。");
DesktopPaths.ResolveTool(path, "usbip");
DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"), "ads-usb");
LocalPortProcesses.EnsureAvailable(port);
}
public async Task StartAsync(string path, int port, string upstream, string leaseFile, Action<string> log, CancellationToken cancellation)
{
usbip = DesktopPaths.ResolveTool(path, "usbip");
var deadline = DateTime.UtcNow.AddSeconds(40);
while (!File.Exists(leaseFile) || (await File.ReadAllTextAsync(leaseFile, cancellation)).Trim() != "true")
{
if (DateTime.UtcNow > deadline) throw new InvalidOperationException("USB 模拟等待设备租约超时。");
await Task.Delay(150, cancellation);
}
var executable = DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"), "ads-usb");
bridge = new Process { StartInfo = ProcessTools.CreateStartInfo(executable,
["--listen", $"127.0.0.1:{port}", "--upstream", upstream, "--serial", Serial]) };
bridge.OutputDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
bridge.ErrorDataReceived += (_, e) => { if (e.Data != null) log(e.Data); };
bridge.Start(); bridge.BeginOutputReadLine(); bridge.BeginErrorReadLine();
deadline = DateTime.UtcNow.AddSeconds(5);
while (true)
{
if (bridge.HasExited) throw new InvalidOperationException("虚拟 USB 设备进程退出,请检查 USB/IP 端口。");
try { using var probe = new TcpClient(); await probe.ConnectAsync(IPAddress.Loopback, port, cancellation); break; }
catch (SocketException) when (DateTime.UtcNow < deadline) { await Task.Delay(100, cancellation); }
}
var attach = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(usbip,
["--tcp-port", port.ToString(), "attach", "--remote", "127.0.0.1", "--bus-id", "1-1", "--terse", "--once"]), cancellation);
if (attach.ExitCode != 0 || !int.TryParse(attach.Output.Trim(), out var importedPort) || importedPort is < 1 or > 127)
throw new InvalidOperationException("虚拟 USB 挂载失败:" + attach.Error.Trim() + " " + attach.Output.Trim());
hubPort = importedPort;
log($"USB ADB 已挂载:{Serial},本机控制器端口 {hubPort}。");
}
public async Task StopAsync(Action<string> log)
{
// Closing our export first forces the driver to remove this device even if detach fails.
var process = bridge; bridge = null;
await ProcessTools.StopAsync(process);
hubPort = null;
// --once creates no persistent retry. TCP EOF removes only our virtual device;
// do not detach by a port number which the driver could already have reused.
log("本次虚拟 USB 设备已断开。");
}
}
+4
View File
@@ -58,3 +58,7 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen
## 集群连接
地址指向控制中心。默认 P2P 优先,连接配置的“仅使用中继”可跳过直连;修改在下次连接生效。连接管理显示实际 P2P/中继节点,控制中心配置卡显示节点健康及通道数。节点健康约每 5 秒由中心探测,桌面刷新设备时读取。
## Windows USB 模拟
连接配置提供可选 USB 模式、usbip.exe 路径和回环 USB/IP 端口;需要已签名的 USBip UDE 控制器。启动时等待设备租约,再导入虚拟设备;监控、设备信息和 scrcpy 使用 USB 序列号。安装与限制见 [Windows USB 文档](../docs/windows-usb.md)。