using DeviceService.Service;
using DeviceService.Service.NamePipe;
using System.Collections.ObjectModel;
using System.IO.Pipes;
using System.Text;
using System.Windows;
using System.Windows.Input;
namespace DeviceService;
///
/// Interaction logic for DebugWindow.xaml
///
public partial class DebugWindow : Window
{
private const string PipeName = "DeviceService";
private class ClientItem
{
public ClientItem(IClient client, string name)
{
Client = client;
Name = name;
}
public IClient Client { get; }
public string Name { get; }
public override string ToString() => Name;
}
private NamePipeService? _pipeService;
private readonly ObservableCollection _clients = new ObservableCollection();
public DebugWindow()
{
InitializeComponent();
ClientList.ItemsSource = _clients;
Loaded += DebugWindow_Loaded;
Closed += DebugWindow_Closed;
}
private void DebugWindow_Loaded(object sender, RoutedEventArgs e)
{
}
private string FindClientName(IClient client)
{
ClientItem? item = _clients.FirstOrDefault(c => ReferenceEquals(c.Client, client));
return item?.Name ?? "未知客户端";
}
private async void SendTestButton_Click(object sender, RoutedEventArgs e)
{
string text = SendBox.Text;
if (string.IsNullOrEmpty(text))
{
return;
}
SendTestButton.IsEnabled = false;
try
{
string error = await Task.Run(() => SendViaPipe(text + "\r\n"));
AppendLine(string.IsNullOrEmpty(error)
? $"[测试] 已发送:{text}"
: $"[测试] 发送失败:{error}");
}
finally
{
SendTestButton.IsEnabled = true;
}
}
private async void SendToClientButton_Click(object sender, RoutedEventArgs e)
{
if (ClientList.SelectedItem is not ClientItem item)
{
AppendLine("[发送] 请先在左侧列表中选择一个客户端。");
return;
}
string text = SendBox.Text;
if (string.IsNullOrEmpty(text))
{
return;
}
string name = item.Name;
IClient client = item.Client;
SendToClientButton.IsEnabled = false;
try
{
string error = await Task.Run(() => client.Send(text, out string err) ? string.Empty : err);
AppendLine(string.IsNullOrEmpty(error)
? $"[发送→{name}] {text}"
: $"[发送失败→{name}] {error}");
}
finally
{
SendToClientButton.IsEnabled = true;
}
}
private void SendBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// 已选中客户端则定向发送,否则走测试通道
if (ClientList.SelectedItem is ClientItem)
{
SendToClientButton_Click(sender, e);
}
else
{
SendTestButton_Click(sender, e);
}
}
}
///
/// 以客户端身份连接本进程的管道,按行协议写入一条 UTF8 消息(以 \n 结尾)。
/// 返回空字符串表示成功,否则为错误信息。
///
private static string SendViaPipe(string text)
{
try
{
using var pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut);
pipe.Connect(2000);
byte[] payload = Encoding.UTF8.GetBytes(text + "\n");
pipe.Write(payload, 0, payload.Length);
pipe.Flush();
return string.Empty;
}
catch (Exception ex)
{
return ex.Message;
}
}
private void AppendLine(string text)
{
ReceiveBox.AppendText(text + Environment.NewLine);
ReceiveBox.ScrollToEnd();
}
private void DebugWindow_Closed(object? sender, EventArgs e)
{
}
}