设备连接

This commit is contained in:
hsc
2026-06-11 17:25:59 +08:00
parent a9ee9e974e
commit a62b6cbc8f
15 changed files with 144 additions and 35 deletions

View File

@@ -1,4 +1,5 @@
using System;
using Model.Models;
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;

View File

@@ -1,4 +1,5 @@
using System;
using Model.Models;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;

View File

@@ -13,6 +13,7 @@
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.Globalization;
using System.Threading;

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.Globalization;
using System.Threading;

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.ComponentModel;
using System.Globalization;

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.Globalization;
using System.Threading;

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.Globalization;
using System.Threading;

View File

@@ -1,5 +1,6 @@
using Common.Attributes;
using DeviceCommand.Base;
using Model.Models;
using System;
using System.Globalization;
using System.Threading;

View File

@@ -46,6 +46,7 @@ namespace MainModule.ViewModels
public ICommand RefreshCommand { get; set; }
public ICommand BackToProtocolCommand { get; set; }
public ICommand LoadedCommand { get; set; }
public AutomatedTestingViewModel(IContainerExtension container) : base(container)
{
@@ -75,8 +76,10 @@ namespace MainModule.ViewModels
ParametersManagerVM = _scope.Resolve<ParametersManagerViewModel>();
RefreshCommand = new DelegateCommand(OnRefresh);
BackToProtocolCommand = new DelegateCommand(OnBackToProtocol);
LoadedCommand = new AsyncDelegateCommand(OnLoad);
}
public void Dispose()
{
// 1. 如果 TestStatus 为空,说明还没走到 OnNavigatedTo 赋值,直接释放 scope 即可
@@ -114,6 +117,11 @@ namespace MainModule.ViewModels
}
}
#region
private async Task OnLoad()
{
await _deviceManager.ConnectAllDevices();
}
private void OnRefresh()
{
// 双击:把自己的名字扔出去

View File

@@ -15,6 +15,11 @@
<UserControl.Resources>
<converters:LessThanConverter x:Key="LessThanConverter" />
</UserControl.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Border >
<i:Interaction.Behaviors>
<b:MouseDoubleClickBehavior

View File

@@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="SqlSugarCore" Version="5.1.4.215-preview13" />
<PackageReference Include="System.IO.Ports" Version="11.0.0-preview.4.26230.115" />
</ItemGroup>
</Project>

View File

@@ -1,6 +1,6 @@
using System.IO.Ports;
namespace DeviceCommand.Base
namespace Model.Models
{
/// <summary>
/// 串口通信参数DeviceCommand 内部纯数据类,供设备类构造函数使用)。

View File

@@ -1,4 +1,4 @@
namespace DeviceCommand.Base
namespace Model.Models
{
/// <summary>
/// TCP 通信参数DeviceCommand 内部纯数据类,供设备类构造函数使用)。

View File

@@ -1,5 +1,6 @@
using DeviceCommand.Base;
using Logger;
using Model.Models;
using Prism.Ioc;
using System;
using System.Collections.Generic;
@@ -29,29 +30,7 @@ namespace UIShare.GlobalVariable
{
_systemConfig = systemConfig;
InitDevices();
}
/// <summary>
/// 扫描 <see cref="IBaseInterface"/> 所在程序集中所有可实例化的实现类,
/// 以类型名为键建立映射。这样新增设备类无需修改 DeviceManager。
/// </summary>
private static IReadOnlyDictionary<string, Type> BuildDeviceTypeMap()
{
try
{
return typeof(IBaseInterface).Assembly
.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract && typeof(IBaseInterface).IsAssignableFrom(t))
.ToDictionary(t => t.Name, t => t, StringComparer.OrdinalIgnoreCase);
}
catch (ReflectionTypeLoadException ex)
{
LoggerHelper.Error($"扫描设备类型失败:{ex.Message}");
return new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
}
}
private void InitDevices()
{
DeviceMap = new Dictionary<string, IBaseInterface>(StringComparer.OrdinalIgnoreCase);
@@ -98,10 +77,121 @@ namespace UIShare.GlobalVariable
}
}
/// <summary>
/// 实例化 TCP 类设备:将 <see cref="TcpConfigVM"/> 转为 <see cref="TcpConfig"/> POCO
/// 调用设备类的 (TcpConfig) 构造函数。
/// </summary>
public async Task ConnectAllDevices(CancellationToken ct = default)
{
if (_systemConfig?.DeviceList == null || DeviceMap.Count == 0) return;
var tasks = new List<Task>();
foreach (var info in _systemConfig.DeviceList)
{
if (info == null || !info.IsEnabled) continue;
if (string.IsNullOrWhiteSpace(info.DeviceName)) continue;
if (!DeviceMap.TryGetValue(info.DeviceName, out var device)) continue;
tasks.Add(ConnectInternalAsync(info, device, ct));
}
await Task.WhenAll(tasks);
}
public async Task ConnectSpecifiedDevice(string deviceName, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(deviceName))
{
LoggerHelper.Warn("ConnectSpecifiedDevice设备名为空。");
return;
}
if (!DeviceMap.TryGetValue(deviceName, out var device))
{
LoggerHelper.Warn($"ConnectSpecifiedDevice未找到设备 [{deviceName}]。");
return;
}
var info = _systemConfig?.DeviceList?
.FirstOrDefault(d => d != null && string.Equals(d.DeviceName, deviceName, StringComparison.OrdinalIgnoreCase));
await ConnectInternalAsync(info, device, ct);
}
private async Task ConnectInternalAsync(DeviceInfoVM? info, IBaseInterface device, CancellationToken ct)
{
string name = info?.DeviceName ?? device.GetType().Name;
string conn = info?.ConnectionType ?? "?";
try
{
if (device.IsConnected)
{
if (info != null) info.IsConnected = true;
LoggerHelper.Info($"设备 [{name}] 已连接,跳过。");
return;
}
bool ok = conn switch
{
"Tcp" => await ConnectTcpAsync(name, device, ct),
"Serial" => await ConnectSerialAsync(name, device, ct),
_ => false
};
if (info != null) info.IsConnected = ok;
if (ok)
LoggerHelper.Info($"设备 [{name}/{conn}] 连接成功。");
else
LoggerHelper.Warn($"设备 [{name}/{conn}] 连接失败。");
}
catch (OperationCanceledException)
{
if (info != null) info.IsConnected = false;
LoggerHelper.Warn($"设备 [{name}/{conn}] 连接已取消。");
}
catch (Exception ex)
{
if (info != null) info.IsConnected = false;
var inner = ex.InnerException?.Message ?? ex.Message;
LoggerHelper.ErrorWithNotify($"设备 [{name}/{conn}] 连接异常:{inner}");
}
}
private static async Task<bool> ConnectTcpAsync(string name, IBaseInterface device, CancellationToken ct)
{
if (device is not ITcp tcp)
{
LoggerHelper.Warn($"设备 [{name}] 配置为 Tcp 但未实现 ITcp实际类型为 {device.GetType().Name}。");
return false;
}
return await tcp.ConnectAsync(ct);
}
private static async Task<bool> ConnectSerialAsync(string name, IBaseInterface device, CancellationToken ct)
{
if (device is not ISerialPort sp)
{
LoggerHelper.Warn($"设备 [{name}] 配置为 Serial 但未实现 ISerialPort实际类型为 {device.GetType().Name}。");
return false;
}
return await sp.ConnectAsync(ct);
}
#region
private static IReadOnlyDictionary<string, Type> BuildDeviceTypeMap()
{
try
{
return typeof(IBaseInterface).Assembly
.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract && typeof(IBaseInterface).IsAssignableFrom(t))
.ToDictionary(t => t.Name, t => t, StringComparer.OrdinalIgnoreCase);
}
catch (ReflectionTypeLoadException ex)
{
LoggerHelper.Error($"扫描设备类型失败:{ex.Message}");
return new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
}
}
private static IBaseInterface? CreateTcpDevice(Type type, TcpConfigVM? vm)
{
vm ??= new TcpConfigVM();
@@ -114,11 +204,6 @@ namespace UIShare.GlobalVariable
};
return Activator.CreateInstance(type, cfg) as IBaseInterface;
}
/// <summary>
/// 实例化串口类设备:将 <see cref="SerialPortConfigVM"/> 转为 <see cref="SerialPortConfig"/> POCO
/// StopBits / Parity 从字符串解析为枚举,调用设备类的 (SerialPortConfig) 构造函数。
/// </summary>
private static IBaseInterface? CreateSerialDevice(Type type, SerialPortConfigVM? vm)
{
vm ??= new SerialPortConfigVM();
@@ -134,5 +219,6 @@ namespace UIShare.GlobalVariable
};
return Activator.CreateInstance(type, cfg) as IBaseInterface;
}
#endregion
}
}