设备编辑1

This commit is contained in:
hsc
2026-06-12 09:25:40 +08:00
parent a62b6cbc8f
commit ffb22e1f20
3 changed files with 111 additions and 19 deletions

View File

@@ -17,6 +17,7 @@ namespace UIShare.GlobalVariable
/// </summary>
public class DeviceManager
{
private object _lockObj = new object();
public SystemConfig _systemConfig { get; set; }
/// <summary>按 DeviceName 索引的设备字典,便于业务层按名取实例。</summary>
@@ -115,7 +116,86 @@ namespace UIShare.GlobalVariable
await ConnectInternalAsync(info, device, ct);
}
/// <summary>
/// 异步关闭指定设备,释放底层连接并更新 UI 状态
/// </summary>
public async Task CloseDeviceAsync(string deviceName)
{
if (string.IsNullOrWhiteSpace(deviceName)) return;
IBaseInterface? device;
DeviceInfoVM? info;
lock (_lockObj)
{
if (!DeviceMap.TryGetValue(deviceName, out device)) return;
info = _systemConfig?.DeviceList?
.FirstOrDefault(d => d != null && string.Equals(d.DeviceName, deviceName, StringComparison.OrdinalIgnoreCase));
}
await CloseInternalAsync(info, device);
}
/// <summary>
/// 异步关闭所有设备
/// </summary>
public async Task CloseAllDevicesAsync()
{
List<Task> tasks = new List<Task>();
lock (_lockObj)
{
if (DeviceMap.Count == 0) return;
foreach (var kvp in DeviceMap)
{
string deviceName = kvp.Key;
var device = kvp.Value;
var info = _systemConfig?.DeviceList?
.FirstOrDefault(d => d != null && string.Equals(d.DeviceName, deviceName, StringComparison.OrdinalIgnoreCase));
tasks.Add(CloseInternalAsync(info, device));
}
}
await Task.WhenAll(tasks);
LoggerHelper.Info("所有设备已执行关闭操作。");
}
#region
private async Task CloseInternalAsync(DeviceInfoVM? info, IBaseInterface device)
{
string name = info?.DeviceName ?? device.GetType().Name;
string conn = info?.ConnectionType ?? "?";
try
{
// 如果设备本身已经是断开状态,直接更新 UI 并返回
if (!device.IsConnected)
{
if (info != null) info.IsConnected = false;
LoggerHelper.Info($"设备 [{name}] 本就处于断开状态。");
return;
}
await Task.Run(() => device.Close());
LoggerHelper.Info($"设备 [{name}/{conn}] 已成功关闭连接。");
}
catch (Exception ex)
{
var inner = ex.InnerException?.Message ?? ex.Message;
LoggerHelper.Error($"设备 [{name}/{conn}] 关闭连接时出现异常: {inner}");
}
finally
{
// 无论关闭时是否抛出异常,均强制同步 UI 状态为未连接
if (info != null)
{
info.IsConnected = false;
}
}
}
private async Task ConnectInternalAsync(DeviceInfoVM? info, IBaseInterface device, CancellationToken ct)
{
string name = info?.DeviceName ?? device.GetType().Name;
@@ -176,7 +256,6 @@ namespace UIShare.GlobalVariable
}
return await sp.ConnectAsync(ct);
}
#region
private static IReadOnlyDictionary<string, Type> BuildDeviceTypeMap()
{
try