Files
AndroidDeviceStreaming/desktop/Ads.Desktop/WindowsUsbSession.cs
T

73 lines
4.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 设备已断开。");
}
}