设备连接

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,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
}
}