feat: support Linux virtual USB in Avalonia desktop
This commit is contained in:
1 parent
ac8eb72319
commit
de6ecae54f
8 files changed
+42
-12
No files matched your search
@@ -47,7 +47,7 @@
|
||||
|
||||
## 可选 USB 模拟功能(Windows 已开始实现)
|
||||
|
||||
用户于 2026-11-12 授权新增可选 USB 模拟,先实现 Windows。当前采用独立 Rust USB/IP 虚拟 ADB 设备 + 已签名的 USBip UDE 控制器,复用现有网络隧道,包含桌面开关、驱动检测和安装脚本;详见 docs/windows-usb.md。Linux 已按 2026-11-13 新授权完成原生 USB/IP CLI 验证,见 docs/linux-usb.md;Linux GUI 尚未接入。macOS 仍仅记录方案。以下跨平台内容保留为设计依据。
|
||||
用户于 2026-11-12 授权新增可选 USB 模拟,先实现 Windows。当前采用独立 Rust USB/IP 虚拟 ADB 设备 + 已签名的 USBip UDE 控制器,复用现有网络隧道,包含桌面开关、驱动检测和安装脚本;详见 docs/windows-usb.md。Linux 已按 2026-11-13 新授权完成原生 USB/IP CLI 验证,见 docs/linux-usb.md;Avalonia Linux GUI 已接入 pkexec 挂载;Flutter Linux GUI 尚未接入。macOS 仍仅记录方案。以下跨平台内容保留为设计依据。
|
||||
|
||||
### 目标与范围
|
||||
|
||||
|
||||
@@ -228,4 +228,4 @@ Agent 管理发行入口:`scripts/build-desktop.ps1` 生成 `bin/desktop-win-x
|
||||
|
||||
Linux 安装包:`bash scripts/build-linux-packages.sh`,提供 `.deb` 和 `.tar.gz`,详见 [Linux 打包](docs/linux-packaging.md)。
|
||||
|
||||
Linux 原生虚拟 USB 已在 Ubuntu 实机通过 CLI 验证,部署和权限说明见 [Linux USB](docs/linux-usb.md)。Linux GUI 开关尚未接入。
|
||||
Linux 原生虚拟 USB 已在 Ubuntu 实机通过 CLI 验证,部署和权限说明见 [Linux USB](docs/linux-usb.md)。Avalonia Linux GUI 已接入 pkexec 挂载,Flutter Linux 尚未接入。
|
||||
@@ -34,7 +34,7 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
private int missingUsbPolls, recoveryAttempts, stablePolls;
|
||||
private DateTime nextRecovery=DateTime.MinValue;
|
||||
private CancellationTokenSource? recoveryCancellation;
|
||||
private WindowsUsbSession? usb;
|
||||
private UsbSession? usb;
|
||||
private string? transportFile, leaseFile;
|
||||
private readonly Action<string> log;
|
||||
private readonly SemaphoreSlim gate = new(1, 1);
|
||||
@@ -73,7 +73,7 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
Model = AndroidVersion = ApiLevel = "—";
|
||||
log($"连接已启动,隧道 {RawEndpoint}。");
|
||||
if (Options.UsbMode) {
|
||||
usb = new WindowsUsbSession(DeviceId);
|
||||
usb = new UsbSession(DeviceId);
|
||||
await usb.StartAsync(Options.Usbip, Options.UsbPort!.Value, RawEndpoint, leaseFile!, log, lifetime.Token);
|
||||
Endpoint = usb.Serial;
|
||||
}
|
||||
@@ -163,7 +163,7 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
}
|
||||
var newPort=ConnectionPorts.Allocate(Options.UsbPort is >=65535 ?3240:Options.UsbPort!.Value+1,new[]{Options.Port,ScreenPort??0});
|
||||
Options=Options with {UsbPort=newPort};OnPropertyChanged(nameof(PortSummary));
|
||||
usb=new WindowsUsbSession(DeviceId);
|
||||
usb=new UsbSession(DeviceId);
|
||||
await usb.StartAsync(Options.Usbip,newPort,RawEndpoint,leaseFile!,log,cancellation);
|
||||
Endpoint=usb.Serial;usbBroken=false;Status="USB 已重新挂载 · 等待 ADB 就绪";
|
||||
} catch(OperationCanceledException) when(cancellation.IsCancellationRequested) { }
|
||||
|
||||
@@ -25,7 +25,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
[ObservableProperty] private int maxSize = 1920;
|
||||
[ObservableProperty] private int maxFps = 60;
|
||||
[ObservableProperty] private bool usbMode;
|
||||
[ObservableProperty] private string usbipPath = WindowsUsbSession.DefaultUsbipPath();
|
||||
[ObservableProperty] private string usbipPath = UsbSession.DefaultUsbipPath();
|
||||
[ObservableProperty] private int usbPort = 3240;
|
||||
[ObservableProperty] private bool relayOnly;
|
||||
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
|
||||
@@ -300,7 +300,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
int? usbPort = null;
|
||||
if (UsbMode) {
|
||||
usbPort = ConnectionPorts.Allocate(UsbPort, reserved);
|
||||
WindowsUsbSession.Validate(UsbipPath, usbPort.Value);
|
||||
UsbSession.Validate(UsbipPath, usbPort.Value);
|
||||
}
|
||||
if (sessions.Remove(device.Id, out var old)) { old.PropertyChanged -= ConnectionChanged; old.Dispose(); }
|
||||
var session = new DeviceConnection(device.Id,
|
||||
|
||||
@@ -125,7 +125,7 @@
|
||||
<TextBlock Text="{Binding ToolsStatus}" Classes="label" TextWrapping="Wrap"/>
|
||||
</StackPanel></Border>
|
||||
<Border Classes="card"><StackPanel Spacing="10">
|
||||
<TextBlock Text="可选 USB 模拟 · Windows" Classes="section"/>
|
||||
<TextBlock Text="可选 USB 模拟 · Windows / Linux" Classes="section"/>
|
||||
<CheckBox x:Name="UsbModeCheck" Content="将远程手机挂载为本机 USB ADB 设备" IsChecked="{Binding UsbMode}"/>
|
||||
<TextBlock Text="需要安装 USBip 虚拟控制器驱动。仅模拟 ADB 接口;首次使用仍需手机授权,修改在下次连接生效。" Classes="label" TextWrapping="Wrap"/>
|
||||
<TextBlock Text="usbip.exe 路径"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding UsbipPath}" Watermark="usbip.exe"/><Button Grid.Column="1" Content="选择" Tag="usbip" Click="ChooseToolClick"/></Grid>
|
||||
|
||||
@@ -6,23 +6,29 @@ using Microsoft.Win32;
|
||||
namespace Ads.Desktop;
|
||||
|
||||
/// <summary>Owns one loopback USB/IP export and its exact imported hub port.</summary>
|
||||
public sealed class WindowsUsbSession : IDisposable
|
||||
public sealed class UsbSession : IDisposable
|
||||
{
|
||||
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 UsbSession(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()
|
||||
{
|
||||
if(OperatingSystem.IsLinux())return DesktopPaths.FindTool("usbip");
|
||||
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(OperatingSystem.IsLinux()) {
|
||||
if(port is <1024 or >65535)throw new InvalidOperationException("USB/IP 端口范围为 1024–65535。");
|
||||
DesktopPaths.ResolveTool(path,"usbip");DesktopPaths.ResolveTool(DesktopPaths.FindTool("pkexec"),"pkexec");
|
||||
DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-usb"),"ads-usb");LocalPortProcesses.EnsureAvailable(port);return;
|
||||
}
|
||||
if (!OperatingSystem.IsWindows()) throw new InvalidOperationException("USB 模拟目前支持 Windows 与 Linux。");
|
||||
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 模拟配置中的安装说明。");
|
||||
@@ -52,6 +58,17 @@ public sealed class WindowsUsbSession : IDisposable
|
||||
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); }
|
||||
}
|
||||
if(OperatingSystem.IsLinux()) {
|
||||
if(!Directory.Exists("/sys/module/vhci_hcd")) {
|
||||
var modprobe=new[]{"/usr/sbin/modprobe","/sbin/modprobe"}.FirstOrDefault(File.Exists) ?? throw new InvalidOperationException("未安装 modprobe。");
|
||||
var loaded=await ElevatedAsync(new[]{modprobe,"vhci_hcd"},cancellation);
|
||||
if(loaded.ExitCode!=0)throw new InvalidOperationException("vhci_hcd 加载失败:"+loaded.Error);
|
||||
}
|
||||
log("请求 Linux 系统挂载授权,请确认桌面授权对话框。");
|
||||
var attached=await ElevatedAsync(new[]{usbip!,"--tcp-port",port.ToString(),"attach","--remote","127.0.0.1","--busid","1-1"},cancellation);
|
||||
if(attached.ExitCode!=0)throw new InvalidOperationException("Linux USB 挂载失败:"+attached.Error+attached.Output);
|
||||
log($"Linux USB 已挂载:{Serial}。");return;
|
||||
}
|
||||
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)
|
||||
@@ -59,6 +76,13 @@ public sealed class WindowsUsbSession : IDisposable
|
||||
hubPort = importedPort;
|
||||
log($"USB ADB 已挂载:{Serial},本机控制器端口 {hubPort}。");
|
||||
}
|
||||
private static async Task<ProcessResult> ElevatedAsync(IEnumerable<string> args,CancellationToken cancellation) {
|
||||
using var process=Process.Start(ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("pkexec"),"pkexec"),args)) ?? throw new InvalidOperationException("无法请求系统授权。");
|
||||
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
|
||||
try{await process.WaitForExitAsync(cancellation).WaitAsync(TimeSpan.FromMinutes(2),cancellation);}
|
||||
catch{if(!process.HasExited)process.Kill(entireProcessTree:true);throw;}
|
||||
return new ProcessResult(process.ExitCode,await output,await error);
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
var current = bridge; bridge = null;
|
||||
@@ -86,3 +86,9 @@ Windows 桌面入口与 Flutter 共用同一会话级单实例锁(包括 --age
|
||||
本机工具、USBip、客户端凭据及本机 Agent 配置提供文件选择对话框,选取后立即记忆文件位置。Agent 管理记忆管理员及初始化凭据文件位置,令牌内容仍仅在内存。URL/IP/端口继续按网络地址填写。
|
||||
|
||||
USB 连续缺失 3 轮、USB 后端退出或投屏报告设备断开后,自动等待租约、选择新回环端口重挂载;必要时重启本次 ads-client,并按原分辨率、帧率和控制设置恢复 scrcpy。重试带 2/4/8/16/30 秒退避,等待手机授权时暂停重挂载。主动停止投屏、关闭投屏窗口、主动断开和退出取消相应恢复。其他设备与物理 USB 手机不受影响。
|
||||
|
||||
## Linux 桌面 USB
|
||||
|
||||
USB 会话后端已按操作系统选择:Windows 使用已签名 USBip 控制器,Linux 使用系统 usbip/vhci_hcd,挂载时通过 pkexec 请求桌面授权。转发和 ads-usb 仍以当前用户运行,断开时关闭本次导出,避免按可能复用的控制器端口误断其他设备。Linux 需安装 usbip、polkit、ADB 和兼容版本 scrcpy;首次授权需在手机确认。
|
||||
|
||||
192.168.5.224 工程位于 `/home/tt/TongTongStudio/AndroidDeviceStreaming`,自包含发行目录为 `bin/desktop-linux-x64/`。已在 TT 的 X11 会话启动成功;已有 .NET 8.0.16 runtime 和 SDK 8.0.409 位于 `/home/tt/.dotnet`,SSH PATH 未包含此目录。工程要求 SDK 8.0.428,远程源码构建尚需安装该版本;自包含发行版无需安装 runtime。
|
||||
+1
-1
@@ -44,6 +44,6 @@ sudo systemctl stop ads-linux-usb-monitor ads-usb-export
|
||||
sudo systemctl start ads-linux-usb-monitor
|
||||
```
|
||||
|
||||
已验证原生 `usb:3-1` 枚举、普通 TT 的 adb -d、远程 shell、8 MiB push 的 SHA-256 完整性。目标机原有三个模拟器保持运行。Linux 桌面 UI 的 USB 开关尚未接入,此版本通过 CLI/systemd 使用;MTP、fastboot 和整机 USB 透传不在范围内。目标机既有第三方 APT 源存在 404,部署使用已更新的 Ubuntu 索引,没有改写该源。
|
||||
已验证原生 `usb:3-1` 枚举、普通 TT 的 adb -d、远程 shell、8 MiB push 的 SHA-256 完整性。目标机原有三个模拟器保持运行。Avalonia 桌面已接入 Linux USB 开关,通过 pkexec 请求系统挂载授权;Flutter Linux 宿主仍未接入。CLI/systemd 路径仍可使用;MTP、fastboot 和整机 USB 透传不在范围内。目标机既有第三方 APT 源存在 404,部署使用已更新的 Ubuntu 索引,没有改写该源。
|
||||
|
||||
重挂载测试也已通过:核对来源后仅 detach 本次虚拟端口,监控自动重新导入,adb 重新恢复 device。仓库 deploy/ 下附 export、upstream 和 monitor 三份 systemd 配置示例;安装前按实际账号和路径修改,并拒绝覆盖不属于本项目的同名服务。
|
||||
Reference in new issue
Block a user