196 lines
11 KiB
C#
196 lines
11 KiB
C#
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();
|
||
}
|
||
}
|