初步完成OpcUa设备的开启连接,关闭断开连接的功能
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using DMS.Application.DTOs;
|
||||
using DMS.Application.Events;
|
||||
using DMS.Application.Interfaces;
|
||||
using DMS.Core.Enums;
|
||||
using DMS.Core.Models;
|
||||
using DMS.Infrastructure.Configuration;
|
||||
using DMS.Infrastructure.Interfaces.Services;
|
||||
using DMS.Infrastructure.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using VariableValueChangedEventArgs = DMS.Core.Models.VariableValueChangedEventArgs;
|
||||
|
||||
namespace DMS.Infrastructure.Services
|
||||
{
|
||||
@@ -20,6 +21,7 @@ namespace DMS.Infrastructure.Services
|
||||
private readonly ILogger<OpcUaServiceManager> _logger;
|
||||
private readonly IDataProcessingService _dataProcessingService;
|
||||
private readonly IAppDataCenterService _appDataCenterService;
|
||||
private readonly IEventService _eventService;
|
||||
private readonly OpcUaServiceOptions _options;
|
||||
private readonly ConcurrentDictionary<int, DeviceContext> _deviceContexts;
|
||||
private readonly SemaphoreSlim _semaphore;
|
||||
@@ -28,15 +30,33 @@ namespace DMS.Infrastructure.Services
|
||||
public OpcUaServiceManager(
|
||||
ILogger<OpcUaServiceManager> logger,
|
||||
IDataProcessingService dataProcessingService,
|
||||
IEventService eventService,
|
||||
IAppDataCenterService appDataCenterService,
|
||||
IOptions<OpcUaServiceOptions> options)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_dataProcessingService = dataProcessingService ?? throw new ArgumentNullException(nameof(dataProcessingService));
|
||||
_appDataCenterService = appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService));
|
||||
_dataProcessingService
|
||||
= dataProcessingService ?? throw new ArgumentNullException(nameof(dataProcessingService));
|
||||
_eventService = eventService;
|
||||
_appDataCenterService
|
||||
= appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService));
|
||||
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
|
||||
_deviceContexts = new ConcurrentDictionary<int, DeviceContext>();
|
||||
_semaphore = new SemaphoreSlim(_options.MaxConcurrentConnections, _options.MaxConcurrentConnections);
|
||||
|
||||
_eventService.OnDeviceActiveChanged += OnDeviceActiveChanged;
|
||||
}
|
||||
|
||||
private async void OnDeviceActiveChanged(object? sender, DeviceActiveChangedEventArgs e)
|
||||
{
|
||||
if (e.NewStatus)
|
||||
{
|
||||
await ConnectDeviceAsync(e.DeviceId, CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
await DisconnectDeviceAsync(e.DeviceId, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -64,12 +84,12 @@ namespace DMS.Infrastructure.Services
|
||||
}
|
||||
|
||||
var context = new DeviceContext
|
||||
{
|
||||
Device = device,
|
||||
OpcUaService = new OpcUaService(),
|
||||
Variables = new ConcurrentDictionary<string, VariableDto>(),
|
||||
IsConnected = false
|
||||
};
|
||||
{
|
||||
Device = device,
|
||||
OpcUaService = new OpcUaService(),
|
||||
Variables = new ConcurrentDictionary<string, VariableDto>(),
|
||||
IsConnected = false
|
||||
};
|
||||
|
||||
_deviceContexts.AddOrUpdate(device.Id, context, (key, oldValue) => context);
|
||||
_logger.LogInformation("已添加设备 {DeviceId} 到监控列表", device.Id);
|
||||
@@ -99,6 +119,7 @@ namespace DMS.Infrastructure.Services
|
||||
{
|
||||
context.Variables.AddOrUpdate(variable.OpcUaNodeId, variable, (key, oldValue) => variable);
|
||||
}
|
||||
|
||||
_logger.LogInformation("已更新设备 {DeviceId} 的变量列表,共 {Count} 个变量", deviceId, variables.Count);
|
||||
}
|
||||
}
|
||||
@@ -139,23 +160,29 @@ namespace DMS.Infrastructure.Services
|
||||
if (context == null || string.IsNullOrEmpty(context.Device.OpcUaServerUrl))
|
||||
return;
|
||||
|
||||
if (!context.Device.IsActive)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _semaphore.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("正在连接设备 {DeviceName} ({EndpointUrl})",
|
||||
context.Device.Name, context.Device.OpcUaServerUrl);
|
||||
_logger.LogInformation("正在连接设备 {DeviceName} ({EndpointUrl})",
|
||||
context.Device.Name, context.Device.OpcUaServerUrl);
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
|
||||
// 设置连接超时
|
||||
using var timeoutToken = new CancellationTokenSource(_options.ConnectionTimeoutMs);
|
||||
using var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token);
|
||||
|
||||
using var linkedToken
|
||||
= CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken.Token);
|
||||
|
||||
await context.OpcUaService.ConnectAsync(context.Device.OpcUaServerUrl);
|
||||
|
||||
|
||||
stopwatch.Stop();
|
||||
_logger.LogInformation("设备 {DeviceName} 连接耗时 {ElapsedMs} ms",
|
||||
context.Device.Name, stopwatch.ElapsedMilliseconds);
|
||||
_logger.LogInformation("设备 {DeviceName} 连接耗时 {ElapsedMs} ms",
|
||||
context.Device.Name, stopwatch.ElapsedMilliseconds);
|
||||
|
||||
if (context.OpcUaService.IsConnected)
|
||||
{
|
||||
@@ -170,8 +197,8 @@ namespace DMS.Infrastructure.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "连接设备 {DeviceName} 时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
_logger.LogError(ex, "连接设备 {DeviceName} 时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
context.IsConnected = false;
|
||||
}
|
||||
finally
|
||||
@@ -197,8 +224,8 @@ namespace DMS.Infrastructure.Services
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "断开设备 {DeviceName} 连接时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
_logger.LogError(ex, "断开设备 {DeviceName} 连接时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,13 +239,13 @@ namespace DMS.Infrastructure.Services
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("正在为设备 {DeviceName} 设置订阅,变量数: {VariableCount}",
|
||||
context.Device.Name, context.Variables.Count);
|
||||
_logger.LogInformation("正在为设备 {DeviceName} 设置订阅,变量数: {VariableCount}",
|
||||
context.Device.Name, context.Variables.Count);
|
||||
|
||||
// 按PollingInterval对变量进行分组
|
||||
var variablesByPollingInterval = context.Variables.Values
|
||||
.GroupBy(v => v.PollingInterval)
|
||||
.ToDictionary(g => g.Key, g => g.ToList());
|
||||
.GroupBy(v => v.PollingInterval)
|
||||
.ToDictionary(g => g.Key, g => g.ToList());
|
||||
|
||||
// 为每个PollingInterval组设置单独的订阅
|
||||
foreach (var group in variablesByPollingInterval)
|
||||
@@ -226,7 +253,8 @@ namespace DMS.Infrastructure.Services
|
||||
int pollingInterval = group.Key;
|
||||
var variables = group.Value;
|
||||
|
||||
_logger.LogInformation("为设备 {DeviceName} 设置PollingInterval {PollingInterval} 的订阅,变量数: {VariableCount}",
|
||||
_logger.LogInformation(
|
||||
"为设备 {DeviceName} 设置PollingInterval {PollingInterval} 的订阅,变量数: {VariableCount}",
|
||||
context.Device.Name, pollingInterval, variables.Count);
|
||||
|
||||
// 根据PollingInterval计算发布间隔和采样间隔(毫秒)
|
||||
@@ -234,19 +262,19 @@ namespace DMS.Infrastructure.Services
|
||||
// var samplingInterval = GetSamplingIntervalFromPollLevel(pollLevel);
|
||||
|
||||
var opcUaNodes = variables
|
||||
.Select(v => new OpcUaNode { NodeId = v.OpcUaNodeId })
|
||||
.ToList();
|
||||
.Select(v => new OpcUaNode { NodeId = v.OpcUaNodeId })
|
||||
.ToList();
|
||||
|
||||
context.OpcUaService.SubscribeToNode(opcUaNodes, HandleDataChanged,
|
||||
publishingInterval, publishingInterval);
|
||||
context.OpcUaService.SubscribeToNode(opcUaNodes, HandleDataChanged,
|
||||
publishingInterval, publishingInterval);
|
||||
}
|
||||
|
||||
_logger.LogInformation("设备 {DeviceName} 订阅设置完成", context.Device.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "为设备 {DeviceName} 设置订阅时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
_logger.LogError(ex, "为设备 {DeviceName} 设置订阅时发生错误: {ErrorMessage}",
|
||||
context.Device.Name, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,24 +285,23 @@ namespace DMS.Infrastructure.Services
|
||||
{
|
||||
// 根据轮询间隔值映射到发布间隔
|
||||
return pollingInterval switch
|
||||
{
|
||||
100 => 100, // HundredMilliseconds -> 100ms发布间隔
|
||||
500 => 500, // FiveHundredMilliseconds -> 500ms发布间隔
|
||||
1000 => 1000, // OneSecond -> 1000ms发布间隔
|
||||
5000 => 5000, // FiveSeconds -> 5000ms发布间隔
|
||||
10000 => 10000, // TenSeconds -> 10000ms发布间隔
|
||||
20000 => 20000, // TwentySeconds -> 20000ms发布间隔
|
||||
30000 => 30000, // ThirtySeconds -> 30000ms发布间隔
|
||||
60000 => 60000, // OneMinute -> 60000ms发布间隔
|
||||
300000 => 300000, // FiveMinutes -> 300000ms发布间隔
|
||||
600000 => 600000, // TenMinutes -> 600000ms发布间隔
|
||||
1800000 => 1800000, // ThirtyMinutes -> 1800000ms发布间隔
|
||||
3600000 => 3600000, // OneHour -> 3600000ms发布间隔
|
||||
_ => _options.SubscriptionPublishingIntervalMs // 默认值
|
||||
};
|
||||
{
|
||||
100 => 100, // HundredMilliseconds -> 100ms发布间隔
|
||||
500 => 500, // FiveHundredMilliseconds -> 500ms发布间隔
|
||||
1000 => 1000, // OneSecond -> 1000ms发布间隔
|
||||
5000 => 5000, // FiveSeconds -> 5000ms发布间隔
|
||||
10000 => 10000, // TenSeconds -> 10000ms发布间隔
|
||||
20000 => 20000, // TwentySeconds -> 20000ms发布间隔
|
||||
30000 => 30000, // ThirtySeconds -> 30000ms发布间隔
|
||||
60000 => 60000, // OneMinute -> 60000ms发布间隔
|
||||
300000 => 300000, // FiveMinutes -> 300000ms发布间隔
|
||||
600000 => 600000, // TenMinutes -> 600000ms发布间隔
|
||||
1800000 => 1800000, // ThirtyMinutes -> 1800000ms发布间隔
|
||||
3600000 => 3600000, // OneHour -> 3600000ms发布间隔
|
||||
_ => _options.SubscriptionPublishingIntervalMs // 默认值
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 处理数据变化
|
||||
@@ -294,12 +321,12 @@ namespace DMS.Infrastructure.Services
|
||||
// 保存旧值
|
||||
var oldValue = variable.DataValue;
|
||||
var newValue = opcUaNode.Value.ToString();
|
||||
|
||||
|
||||
// 更新变量值
|
||||
variable.DataValue = newValue;
|
||||
variable.DisplayValue = newValue;
|
||||
variable.UpdatedAt = DateTime.Now;
|
||||
|
||||
|
||||
_logger.LogDebug($"节点:{variable.OpcUaNodeId}值发生了变化:{newValue}");
|
||||
|
||||
// 触发变量值变更事件
|
||||
@@ -309,8 +336,8 @@ namespace DMS.Infrastructure.Services
|
||||
oldValue,
|
||||
newValue,
|
||||
variable.UpdatedAt);
|
||||
|
||||
_appDataCenterService.VariableManagementService.VariableValueChanged( eventArgs);
|
||||
|
||||
_appDataCenterService.VariableManagementService.VariableValueChanged(eventArgs);
|
||||
|
||||
// 推送到数据处理队列
|
||||
await _dataProcessingService.EnqueueAsync(variable);
|
||||
@@ -341,7 +368,7 @@ namespace DMS.Infrastructure.Services
|
||||
public async Task ConnectDevicesAsync(IEnumerable<int> deviceIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var connectTasks = new List<Task>();
|
||||
|
||||
|
||||
foreach (var deviceId in deviceIds)
|
||||
{
|
||||
if (_deviceContexts.TryGetValue(deviceId, out var context))
|
||||
@@ -349,7 +376,7 @@ namespace DMS.Infrastructure.Services
|
||||
connectTasks.Add(ConnectDeviceAsync(context, cancellationToken));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
await Task.WhenAll(connectTasks);
|
||||
}
|
||||
|
||||
@@ -367,15 +394,16 @@ namespace DMS.Infrastructure.Services
|
||||
/// <summary>
|
||||
/// 批量断开设备连接
|
||||
/// </summary>
|
||||
public async Task DisconnectDevicesAsync(IEnumerable<int> deviceIds, CancellationToken cancellationToken = default)
|
||||
public async Task DisconnectDevicesAsync(IEnumerable<int> deviceIds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var disconnectTasks = new List<Task>();
|
||||
|
||||
|
||||
foreach (var deviceId in deviceIds)
|
||||
{
|
||||
disconnectTasks.Add(DisconnectDeviceAsync(deviceId, cancellationToken));
|
||||
}
|
||||
|
||||
|
||||
await Task.WhenAll(disconnectTasks);
|
||||
}
|
||||
|
||||
@@ -399,11 +427,12 @@ namespace DMS.Infrastructure.Services
|
||||
|
||||
// 断开所有设备连接
|
||||
var deviceIds = _deviceContexts.Keys.ToList();
|
||||
DisconnectDevicesAsync(deviceIds).Wait(TimeSpan.FromSeconds(10));
|
||||
DisconnectDevicesAsync(deviceIds)
|
||||
.Wait(TimeSpan.FromSeconds(10));
|
||||
|
||||
// 释放其他资源
|
||||
_semaphore?.Dispose();
|
||||
|
||||
|
||||
_disposed = true;
|
||||
_logger.LogInformation("OPC UA服务管理器资源已释放");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user