修改S7设备的关闭,和开启
This commit is contained in:
10
App.xaml.cs
10
App.xaml.cs
@@ -75,10 +75,6 @@ public partial class App : Application
|
|||||||
|
|
||||||
// 根据配置启动服务
|
// 根据配置启动服务
|
||||||
var connectionSettings = PMSWPF.Config.ConnectionSettings.Load();
|
var connectionSettings = PMSWPF.Config.ConnectionSettings.Load();
|
||||||
if (connectionSettings.EnableS7Service)
|
|
||||||
{
|
|
||||||
Host.Services.GetRequiredService<S7BackgroundService>().StartService();
|
|
||||||
}
|
|
||||||
if (connectionSettings.EnableMqttService)
|
if (connectionSettings.EnableMqttService)
|
||||||
{
|
{
|
||||||
Host.Services.GetRequiredService<MqttBackgroundService>().StartService();
|
Host.Services.GetRequiredService<MqttBackgroundService>().StartService();
|
||||||
@@ -92,10 +88,6 @@ public partial class App : Application
|
|||||||
protected override async void OnExit(ExitEventArgs e)
|
protected override async void OnExit(ExitEventArgs e)
|
||||||
{
|
{
|
||||||
// 停止服务
|
// 停止服务
|
||||||
Host.Services.GetRequiredService<S7BackgroundService>().StopService();
|
|
||||||
Host.Services.GetRequiredService<MqttBackgroundService>().StopService();
|
|
||||||
Host.Services.GetRequiredService<OpcUaBackgroundService>().StopService();
|
|
||||||
|
|
||||||
await Host.StopAsync();
|
await Host.StopAsync();
|
||||||
Host.Dispose();
|
Host.Dispose();
|
||||||
LogManager.Shutdown();
|
LogManager.Shutdown();
|
||||||
@@ -108,7 +100,7 @@ public partial class App : Application
|
|||||||
services.AddSingleton<NavgatorServices>();
|
services.AddSingleton<NavgatorServices>();
|
||||||
services.AddSingleton<IDialogService, DialogService>();
|
services.AddSingleton<IDialogService, DialogService>();
|
||||||
services.AddSingleton<GrowlNotificationService>();
|
services.AddSingleton<GrowlNotificationService>();
|
||||||
services.AddSingleton<S7BackgroundService>();
|
services.AddHostedService<S7BackgroundService>();
|
||||||
services.AddSingleton<MqttBackgroundService>();
|
services.AddSingleton<MqttBackgroundService>();
|
||||||
services.AddSingleton<OpcUaBackgroundService>();
|
services.AddSingleton<OpcUaBackgroundService>();
|
||||||
|
|
||||||
|
|||||||
@@ -61,6 +61,9 @@ public partial class DataServices : ObservableRecipient, IRecipient<LoadMessage>
|
|||||||
// MQTT列表变更事件,当MQTT配置数据更新时触发。
|
// MQTT列表变更事件,当MQTT配置数据更新时触发。
|
||||||
public event Action<List<Mqtt>> OnMqttListChanged;
|
public event Action<List<Mqtt>> OnMqttListChanged;
|
||||||
|
|
||||||
|
// 设备IsActive状态变更事件,当单个设备的IsActive状态改变时触发。
|
||||||
|
public event Action<Device, bool> OnDeviceIsActiveChanged;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当_mqtts属性值改变时触发的局部方法,用于调用OnMqttListChanged事件。
|
/// 当_mqtts属性值改变时触发的局部方法,用于调用OnMqttListChanged事件。
|
||||||
@@ -133,10 +136,41 @@ public partial class DataServices : ObservableRecipient, IRecipient<LoadMessage>
|
|||||||
/// <returns>表示异步操作的任务。</returns>
|
/// <returns>表示异步操作的任务。</returns>
|
||||||
private async Task LoadDevices()
|
private async Task LoadDevices()
|
||||||
{
|
{
|
||||||
|
// 取消订阅旧设备的属性变更事件,防止内存泄漏
|
||||||
|
if (Devices != null)
|
||||||
|
{
|
||||||
|
foreach (var device in Devices)
|
||||||
|
{
|
||||||
|
device.PropertyChanged -= Device_PropertyChanged;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Devices = await _deviceRepository.GetAll();
|
Devices = await _deviceRepository.GetAll();
|
||||||
|
|
||||||
|
// 订阅新设备的属性变更事件
|
||||||
|
if (Devices != null)
|
||||||
|
{
|
||||||
|
foreach (var device in Devices)
|
||||||
|
{
|
||||||
|
device.PropertyChanged += Device_PropertyChanged;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
OnDeviceListChanged?.Invoke(Devices);
|
OnDeviceListChanged?.Invoke(Devices);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void Device_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (e.PropertyName == nameof(Device.IsActive))
|
||||||
|
{
|
||||||
|
if (sender is Device device)
|
||||||
|
{
|
||||||
|
NlogHelper.Info($"设备 {device.Name} 的IsActive状态改变为 {device.IsActive},触发设备IsActive状态变更事件。");
|
||||||
|
OnDeviceIsActiveChanged?.Invoke(device, device.IsActive);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 异步加载菜单数据,并进行父级关联和排序。
|
/// 异步加载菜单数据,并进行父级关联和排序。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
|
|
||||||
namespace PMSWPF.Services;
|
|
||||||
|
|
||||||
internal class DemoBackgroundService : BackgroundService
|
|
||||||
{
|
|
||||||
private int count = 0;
|
|
||||||
|
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
||||||
{
|
|
||||||
// while (!stoppingToken.IsCancellationRequested)
|
|
||||||
// {
|
|
||||||
// await Task.Delay(1000);
|
|
||||||
// count += 1;
|
|
||||||
// var msg = new MyMessage(35) { Count = count };
|
|
||||||
// WeakReferenceMessenger.Default.Send<MyMessage>(msg);
|
|
||||||
// Console.WriteLine("Hello");
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using PMSWPF.Enums;
|
using PMSWPF.Enums;
|
||||||
using PMSWPF.Helper;
|
using PMSWPF.Helper;
|
||||||
using PMSWPF.Models;
|
using PMSWPF.Models;
|
||||||
@@ -10,40 +12,36 @@ namespace PMSWPF.Services
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// S7后台服务,继承自BackgroundService,用于在后台周期性地轮询S7 PLC设备数据。
|
/// S7后台服务,继承自BackgroundService,用于在后台周期性地轮询S7 PLC设备数据。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class S7BackgroundService
|
public class S7BackgroundService : BackgroundService
|
||||||
{
|
{
|
||||||
// 数据服务实例,用于访问和操作应用程序数据,如设备配置。
|
// 数据服务实例,用于访问和操作应用程序数据,如设备配置。
|
||||||
private readonly DataServices _dataServices;
|
private readonly DataServices _dataServices;
|
||||||
|
|
||||||
// 数据处理服务实例,用于将读取到的数据推入处理队列。
|
// 数据处理服务实例,用于将读取到的数据推入处理队列。
|
||||||
private readonly IDataProcessingService _dataProcessingService;
|
private readonly IDataProcessingService _dataProcessingService;
|
||||||
|
|
||||||
// 存储 S7设备,键为设备Id,值为会话对象。
|
// 存储 S7设备,键为设备Id,值为会话对象。
|
||||||
private readonly Dictionary<int, Device> _deviceDic;
|
private readonly ConcurrentDictionary<int, Device> _deviceDic;
|
||||||
|
|
||||||
// 储存所有要轮询更新的变量,键是Device.Id,值是这个设备所有要轮询的变量
|
// 储存所有要轮询更新的变量,键是Device.Id,值是这个设备所有要轮询的变量
|
||||||
private readonly Dictionary<int, List<VariableData>> _pollVariableDic; // Key: VariableData.Id
|
private readonly ConcurrentDictionary<int, List<VariableData>> _pollVariableDic; // Key: VariableData.Id
|
||||||
|
|
||||||
// 存储S7 PLC客户端实例的字典,键为设备ID,值为Plc对象。
|
// 存储S7 PLC客户端实例的字典,键为设备ID,值为Plc对象。
|
||||||
private readonly Dictionary<string, Plc> _s7PlcClientDic;
|
private readonly ConcurrentDictionary<string, Plc> _s7PlcClientDic;
|
||||||
|
|
||||||
// 储存所有变量的字典,方便通过id获取变量对象
|
// 储存所有变量的字典,方便通过id获取变量对象
|
||||||
private readonly Dictionary<int, VariableData> _variableDic;
|
private readonly Dictionary<int, VariableData> _variableDic;
|
||||||
|
|
||||||
// S7轮询一次读取的变量数,不得大于15
|
// S7轮询一次读取的变量数,不得大于15
|
||||||
private readonly int S7PollOnceReadMultipleVars = 9;
|
private readonly int _s7PollOnceReadMultipleVars = 9;
|
||||||
|
|
||||||
// S7轮询一遍后的等待时间
|
// S7轮询一遍后的等待时间
|
||||||
private readonly int S7PollOnceSleepTimeMs = 100;
|
private readonly int _s7PollOnceSleepTimeMs = 100;
|
||||||
|
|
||||||
Dictionary<int, DataItem> _readVariableDic;
|
|
||||||
|
|
||||||
// 轮询数据的线程。
|
|
||||||
private Thread _pollingThread;
|
|
||||||
|
|
||||||
private ManualResetEvent _reloadEvent = new ManualResetEvent(false);
|
|
||||||
private ManualResetEvent _stopEvent = new ManualResetEvent(false);
|
|
||||||
|
|
||||||
|
|
||||||
// 存储S7设备列表。
|
|
||||||
private Thread _serviceMainThread;
|
private readonly SemaphoreSlim _reloadSemaphore = new SemaphoreSlim(0);
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 构造函数,注入数据服务和数据处理服务。
|
/// 构造函数,注入数据服务和数据处理服务。
|
||||||
@@ -54,13 +52,70 @@ namespace PMSWPF.Services
|
|||||||
{
|
{
|
||||||
_dataServices = dataServices;
|
_dataServices = dataServices;
|
||||||
_dataProcessingService = dataProcessingService;
|
_dataProcessingService = dataProcessingService;
|
||||||
_deviceDic = new();
|
_deviceDic = new ConcurrentDictionary<int, Device>();
|
||||||
_pollVariableDic = new();
|
_pollVariableDic = new ConcurrentDictionary<int, List<VariableData>>();
|
||||||
_s7PlcClientDic = new();
|
_s7PlcClientDic = new ConcurrentDictionary<string, Plc>();
|
||||||
_variableDic = new();
|
_variableDic = new();
|
||||||
_readVariableDic = new();
|
|
||||||
// 订阅设备列表变更事件,以便在设备配置更新时重新加载。
|
// 订阅设备列表变更事件,以便在设备配置更新时重新加载。
|
||||||
_dataServices.OnDeviceListChanged += HandleDeviceListChanged;
|
_dataServices.OnDeviceListChanged += HandleDeviceListChanged;
|
||||||
|
// 订阅单个设备IsActive状态变更事件
|
||||||
|
_dataServices.OnDeviceIsActiveChanged += HandleDeviceIsActiveChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
NlogHelper.Info("S7后台服务正在启动。");
|
||||||
|
_reloadSemaphore.Release(); // Initial trigger to load variables and connect
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
await _reloadSemaphore.WaitAsync(stoppingToken); // Wait for a reload signal
|
||||||
|
|
||||||
|
if (stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_dataServices.Devices == null || _dataServices.Devices.Count == 0)
|
||||||
|
{
|
||||||
|
NlogHelper.Info("没有可用的S7设备,等待设备列表更新...");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var isLoaded = LoadVariables();
|
||||||
|
if (!isLoaded)
|
||||||
|
{
|
||||||
|
NlogHelper.Info("加载变量过程中发生了错误,停止后面的操作。");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
await ConnectS7Service(stoppingToken);
|
||||||
|
NlogHelper.Info("S7后台服务开始轮询变量....");
|
||||||
|
|
||||||
|
// 持续轮询,直到取消请求或需要重新加载
|
||||||
|
while (!stoppingToken.IsCancellationRequested && _reloadSemaphore.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
await PollS7VariableOnce(stoppingToken);
|
||||||
|
await Task.Delay(_s7PollOnceSleepTimeMs, stoppingToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
NlogHelper.Info("S7后台服务已停止。");
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
NlogHelper.Error($"S7后台服务运行中发生了错误:{e.Message}", e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await DisconnectAllPlc();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -68,316 +123,316 @@ namespace PMSWPF.Services
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="sender">事件发送者。</param>
|
/// <param name="sender">事件发送者。</param>
|
||||||
/// <param name="devices">更新后的设备列表。</param>
|
/// <param name="devices">更新后的设备列表。</param>
|
||||||
private void HandleDeviceListChanged(List<Device> devices)
|
private async void HandleDeviceListChanged(List<Device> devices)
|
||||||
{
|
{
|
||||||
NlogHelper.Info("设备列表已更改。S7客户端可能需要重新初始化。");
|
NlogHelper.Info("设备列表已更改。S7客户端可能需要重新初始化。");
|
||||||
_reloadEvent.Set();
|
|
||||||
|
|
||||||
|
_reloadSemaphore.Release(); // 触发ExecuteAsync中的全面重新加载
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启动S7后台服务。
|
/// 处理单个设备IsActive状态变更事件。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void StartService()
|
/// <param name="device">发生状态变化的设备。</param>
|
||||||
|
/// <param name="isActive">设备新的IsActive状态。</param>
|
||||||
|
private async void HandleDeviceIsActiveChanged(Device device, bool isActive)
|
||||||
{
|
{
|
||||||
NlogHelper.Info("S7后台服务正在启动。");
|
NlogHelper.Info($"设备 {device.Name} (ID: {device.Id}) 的IsActive状态改变为 {isActive}。");
|
||||||
_reloadEvent.Set();
|
|
||||||
_serviceMainThread = new Thread(Execute);
|
|
||||||
_serviceMainThread.IsBackground = true;
|
|
||||||
_serviceMainThread.Name = "S7ServiceMainThread";
|
|
||||||
_serviceMainThread.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Execute()
|
if (!isActive)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
while (!_stopEvent.WaitOne(0))
|
// 设备变为非活动状态,断开连接
|
||||||
|
if (_s7PlcClientDic.TryRemove(device.Ip, out var plcClient))
|
||||||
{
|
{
|
||||||
_reloadEvent.WaitOne();
|
|
||||||
if (_dataServices.Devices == null || _dataServices.Devices.Count == 0)
|
|
||||||
{
|
|
||||||
_reloadEvent.Reset();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
LoadVariables();
|
|
||||||
ConnectS7Service();
|
|
||||||
if (_pollingThread == null)
|
|
||||||
{
|
|
||||||
_pollingThread = new Thread(PollS7Variable);
|
|
||||||
_pollingThread.IsBackground = true;
|
|
||||||
_pollingThread.Name = "S7ServicePollingThread";
|
|
||||||
_pollingThread.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
_reloadEvent.Reset();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (ThreadInterruptedException tie)
|
|
||||||
{
|
|
||||||
NlogHelper.Error($"S7后台服务主线程关闭。");
|
|
||||||
DisconnectAllPlc();
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
NlogHelper.Error($"S7后台服务主线程运行中发生了错误:{e.Message}",e);
|
|
||||||
DisconnectAllPlc();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void PollS7Variable()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
NlogHelper.Info("S7后台服务开始轮询变量....");
|
|
||||||
while (!_stopEvent.WaitOne(0))
|
|
||||||
{
|
|
||||||
Thread.Sleep(S7PollOnceSleepTimeMs);
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Stopwatch sw = Stopwatch.StartNew();
|
if (plcClient.IsConnected)
|
||||||
// 遍历并读取每个S7变量。
|
|
||||||
foreach (var deviceId in _pollVariableDic.Keys.ToList())
|
|
||||||
{
|
{
|
||||||
if (!_deviceDic.TryGetValue(deviceId, out var device))
|
plcClient.Close();
|
||||||
{
|
NlogHelper.Info($"已断开设备 {device.Name} ({device.Ip}) 的连接。");
|
||||||
NlogHelper.Warn($"S7服务轮询时在deviceDic中没有找到Id为:{deviceId}的设备");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!_s7PlcClientDic.TryGetValue(device.Ip, out var plcClient))
|
|
||||||
{
|
|
||||||
NlogHelper.Warn($"S7服务轮询时没有找到设备I:{deviceId}的初始化好的Plc客户端对象!");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!plcClient.IsConnected)
|
|
||||||
{
|
|
||||||
NlogHelper.Warn($"S7服务轮询时设备:{device.Name},没有连接,正在重新连接...");
|
|
||||||
ConnectS7Service();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!_pollVariableDic.TryGetValue(deviceId, out var variableList))
|
|
||||||
{
|
|
||||||
NlogHelper.Warn($"S7服务轮询时没有找到设备I:{deviceId},要轮询的变量列表!");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
foreach (var variable in variableList)
|
|
||||||
{
|
|
||||||
// 获取变量的轮询间隔。
|
|
||||||
if (!ServiceHelper.PollingIntervals.TryGetValue(variable.PollLevelType, out var interval))
|
|
||||||
{
|
|
||||||
NlogHelper.Info($"未知轮询级别 {variable.PollLevelType},跳过变量 {variable.Name}。");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否达到轮询时间。
|
|
||||||
if ((DateTime.Now - variable.UpdateTime) < interval)
|
|
||||||
continue; // 未到轮询时间,跳过。
|
|
||||||
|
|
||||||
ReadVariableData(variable, plcClient, device);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// sw.Stop();
|
|
||||||
// Console.WriteLine(
|
|
||||||
// $"S7轮询设备数:{_pollVariableDic.Count},共轮询变量数:{varCount},总耗时:{sw.ElapsedMilliseconds}ms");
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
NotificationHelper.ShowError($"S7后台服务在轮询变量过程中发生错误:{ex.Message}", ex);
|
NlogHelper.Error($"断开设备 {device.Name} ({device.Ip}) 连接时发生错误:{ex.Message}", ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
NlogHelper.Info("S7后台服务轮询变量结束。");
|
// 触发重新加载,让LoadVariables和ConnectS7Service处理设备列表的更新
|
||||||
}
|
_reloadSemaphore.Release();
|
||||||
catch (ThreadInterruptedException tie)
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private async Task PollS7VariableOnce(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
NlogHelper.Error($"S7后台服务轮询变量线程关闭。");
|
// 获取当前需要轮询的设备ID列表的快照
|
||||||
DisconnectAllPlc();
|
var deviceIdsToPoll = _pollVariableDic.Keys.ToList();
|
||||||
|
|
||||||
|
// 为每个设备创建并发轮询任务
|
||||||
|
var pollingTasks = deviceIdsToPoll.Select(async deviceId =>
|
||||||
|
{
|
||||||
|
if (!_deviceDic.TryGetValue(deviceId, out var device))
|
||||||
|
{
|
||||||
|
NlogHelper.Warn($"S7服务轮询时在deviceDic中没有找到Id为:{deviceId}的设备");
|
||||||
|
return; // 跳过此设备
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_s7PlcClientDic.TryGetValue(device.Ip, out var plcClient))
|
||||||
|
{
|
||||||
|
NlogHelper.Warn($"S7服务轮询时没有找到设备I:{deviceId}的初始化好的Plc客户端对象!");
|
||||||
|
return; // 跳过此设备
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!plcClient.IsConnected)
|
||||||
|
{
|
||||||
|
NlogHelper.Warn($"S7服务轮询时设备:{device.Name},没有连接,跳过本次轮询。");
|
||||||
|
return; // 跳过此设备,等待ConnectS7Service重新连接
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_pollVariableDic.TryGetValue(deviceId, out var variableList))
|
||||||
|
{
|
||||||
|
NlogHelper.Warn($"S7服务轮询时没有找到设备I:{deviceId},要轮询的变量列表!");
|
||||||
|
return; // 跳过此设备
|
||||||
|
}
|
||||||
|
|
||||||
|
// 轮询当前设备的所有变量
|
||||||
|
var dataItemsToRead = new Dictionary<int, DataItem>(); // Key: VariableData.Id, Value: DataItem
|
||||||
|
var variablesToProcess = new List<VariableData>(); // List of variables to process in this batch
|
||||||
|
|
||||||
|
foreach (var variable in variableList)
|
||||||
|
{
|
||||||
|
if (stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return; // 任务被取消,退出循环
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取变量的轮询间隔。
|
||||||
|
if (!ServiceHelper.PollingIntervals.TryGetValue(
|
||||||
|
variable.PollLevelType, out var interval))
|
||||||
|
{
|
||||||
|
NlogHelper.Info($"未知轮询级别 {variable.PollLevelType},跳过变量 {variable.Name}。");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否达到轮询时间。
|
||||||
|
if ((DateTime.Now - variable.UpdateTime) < interval)
|
||||||
|
continue; // 未到轮询时间,跳过。
|
||||||
|
|
||||||
|
dataItemsToRead[variable.Id] = DataItem.FromAddress(variable.S7Address);
|
||||||
|
variablesToProcess.Add(variable);
|
||||||
|
|
||||||
|
// 达到批量读取数量或已是最后一个变量,执行批量读取
|
||||||
|
if (dataItemsToRead.Count >= _s7PollOnceReadMultipleVars || variable == variableList.Last())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Perform the bulk read
|
||||||
|
await plcClient.ReadMultipleVarsAsync(dataItemsToRead.Values.ToList(),stoppingToken);
|
||||||
|
|
||||||
|
// Process the results
|
||||||
|
foreach (var varData in variablesToProcess)
|
||||||
|
{
|
||||||
|
if (dataItemsToRead.TryGetValue(varData.Id, out var dataItem))
|
||||||
|
{
|
||||||
|
// Now dataItem has the updated value from the PLC
|
||||||
|
await UpdateAndEnqueueVariableData(varData, dataItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
NlogHelper.Error($"从设备 {device.Name} 批量读取变量失败:{ex.Message}", ex);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
dataItemsToRead.Clear();
|
||||||
|
variablesToProcess.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
// 等待所有设备的轮询任务完成
|
||||||
|
await Task.WhenAll(pollingTasks);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (OperationCanceledException)
|
||||||
{
|
{
|
||||||
NlogHelper.Error($"S7后台服务轮询变量线程运行中发生了错误:{e.Message}",e);
|
NlogHelper.Info("S7后台服务轮询变量被取消。");
|
||||||
DisconnectAllPlc();
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
NotificationHelper.ShowError($"S7后台服务在轮询变量过程中发生错误:{ex.Message}", ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 从 PLC 读取变量数据,并将其推送到数据处理队列。
|
/// 更新变量数据,并将其推送到数据处理队列。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="variable">要读取的变量。</param>
|
/// <param name="variable">要更新的变量。</param>
|
||||||
/// <param name="plcClient">S7 PLC 客户端实例。</param>
|
/// <param name="dataItem">包含读取到的数据项。</param>
|
||||||
/// <param name="device">关联的设备。</param>
|
private async Task UpdateAndEnqueueVariableData(VariableData variable, DataItem dataItem)
|
||||||
private async void ReadVariableData(VariableData variable,
|
|
||||||
Plc plcClient, Device device)
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_readVariableDic[variable.Id]=DataItem.FromAddress(variable.S7Address);
|
// 更新变量的原始数据值和显示值。
|
||||||
if (_readVariableDic.Count == S7PollOnceReadMultipleVars)
|
variable.DataValue = dataItem.Value.ToString();
|
||||||
{
|
variable.UpdateTime = DateTime.Now;
|
||||||
// 批量读取
|
// 将更新后的数据推入处理队列。
|
||||||
plcClient.ReadMultipleVars(_readVariableDic.Values.ToList());
|
await _dataProcessingService.EnqueueAsync(variable);
|
||||||
// 批量读取后还原结果
|
|
||||||
foreach (var varId in _readVariableDic.Keys.ToList())
|
|
||||||
{
|
|
||||||
DataItem dataItem = _readVariableDic[varId];
|
|
||||||
if (!_variableDic.TryGetValue(varId, out var variableData))
|
|
||||||
{
|
|
||||||
NlogHelper.Warn($"S7后台服务批量读取变量后,还原值,在_variableDic中找不到ID为{varId}的变量");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// 更新变量的原始数据值和显示值。
|
|
||||||
variableData.DataValue = dataItem.Value.ToString();
|
|
||||||
variableData.UpdateTime = DateTime.Now;
|
|
||||||
// 将更新后的数据推入处理队列,而不是直接在控制台输出。
|
|
||||||
await _dataProcessingService.EnqueueAsync(variableData);
|
|
||||||
}
|
|
||||||
|
|
||||||
_readVariableDic.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
NlogHelper.Error($"从设备 {device.Name} 读取变量 {variable.Name} 失败:{ex.Message}",ex);
|
NlogHelper.Error($"更新变量 {variable.Name} 并入队失败:{ex.Message}", ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ConnectS7Service()
|
private async Task ConnectS7Service(CancellationToken stoppingToken)
|
||||||
{
|
{
|
||||||
|
if (stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var connectTasks = new List<Task>();
|
||||||
|
|
||||||
|
// 遍历_deviceDic中的所有设备,尝试连接
|
||||||
|
foreach (var device in _deviceDic.Values.ToList())
|
||||||
|
{
|
||||||
|
connectTasks.Add(ConnectSingleDeviceAsync(device, stoppingToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.WhenAll(connectTasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 连接单个S7 PLC设备。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="device">要连接的设备。</param>
|
||||||
|
/// <param name="stoppingToken">取消令牌。</param>
|
||||||
|
private async Task ConnectSingleDeviceAsync(Device device, CancellationToken stoppingToken = default)
|
||||||
|
{
|
||||||
|
if (stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if already connected
|
||||||
|
if (_s7PlcClientDic.TryGetValue(device.Ip, out var existingPlc))
|
||||||
|
{
|
||||||
|
if (existingPlc.IsConnected)
|
||||||
|
{
|
||||||
|
NlogHelper.Info($"已连接到 S7 服务器: {device.Ip}:{device.Prot}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Remove disconnected PLC from dictionary to attempt reconnection
|
||||||
|
_s7PlcClientDic.TryRemove(device.Ip, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
NlogHelper.Info($"开始连接S7 PLC: {device.Name} ({device.Ip})");
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// 检查字典中是否已存在该设备的PLC客户端。
|
var plcClient = new Plc(device.CpuType, device.Ip, (short)device.Prot, device.Rack, device.Slot);
|
||||||
foreach (var device in _deviceDic.Values.ToList())
|
await plcClient.OpenAsync(stoppingToken); // 尝试打开连接。
|
||||||
{
|
|
||||||
if (_s7PlcClientDic.TryGetValue(device.Ip, out var plc))
|
|
||||||
{
|
|
||||||
NlogHelper.Info($"已连接到 OPC UA 服务器: {device.Ip}:{device.Prot}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果不存在或者没有连接,则创建新的Plc客户端。
|
_s7PlcClientDic.AddOrUpdate(device.Ip, plcClient, (key, oldValue) => plcClient);
|
||||||
var plcClient = new Plc(device.CpuType, device.Ip, (short)device.Prot, device.Rack, device.Slot);
|
|
||||||
plcClient.Open(); // 尝试打开连接。
|
|
||||||
// 将新创建的客户端添加到字典。
|
|
||||||
_s7PlcClientDic[device.Ip] = plcClient;
|
|
||||||
|
|
||||||
NotificationHelper.ShowSuccess($"已连接到S7 PLC: {device.Name} ({device.Ip})");
|
NotificationHelper.ShowSuccess($"已连接到S7 PLC: {device.Name} ({device.Ip})");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
NotificationHelper.ShowError($"S7服务连接PLC的过程中发生错误:{e}");
|
NotificationHelper.ShowError($"S7服务连接PLC {device.Name} ({device.Ip}) 过程中发生错误:{e.Message}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 加载变量
|
/// 加载变量
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void LoadVariables()
|
private bool LoadVariables()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_deviceDic.Clear();
|
_deviceDic.Clear();
|
||||||
_pollVariableDic.Clear();
|
_pollVariableDic.Clear();
|
||||||
|
_variableDic.Clear(); // 确保在重新加载变量时清空此字典
|
||||||
|
|
||||||
NlogHelper.Info("开始加载S7变量....");
|
NlogHelper.Info("开始加载S7变量....");
|
||||||
var _s7Devices = _dataServices
|
var s7Devices = _dataServices
|
||||||
.Devices.Where(d => d.IsActive == true && d.ProtocolType == ProtocolType.S7)
|
.Devices.Where(d => d.IsActive == true && d.ProtocolType == ProtocolType.S7)
|
||||||
.ToList();
|
.ToList(); // 转换为列表,避免多次枚举
|
||||||
int varCount = 0;
|
|
||||||
foreach (var device in _s7Devices)
|
int totalVariableCount = 0;
|
||||||
|
foreach (var device in s7Devices)
|
||||||
{
|
{
|
||||||
device.IsRuning = true;
|
device.IsRuning = true;
|
||||||
_deviceDic.Add(device.Id, device);
|
_deviceDic.AddOrUpdate(device.Id, device, (key, oldValue) => device);
|
||||||
|
|
||||||
// 过滤出当前设备和S7协议相关的变量。
|
// 过滤出当前设备和S7协议相关的变量。
|
||||||
var s7Variables = device.VariableTables
|
var deviceS7Variables = device.VariableTables
|
||||||
.Where(vt => vt.ProtocolType == ProtocolType.S7 && vt.IsActive)
|
.Where(vt => vt.ProtocolType == ProtocolType.S7 && vt.IsActive)
|
||||||
.SelectMany(vt => vt.DataVariables)
|
.SelectMany(vt => vt.DataVariables)
|
||||||
.Where(vd => vd.IsActive == true)
|
.Where(vd => vd.IsActive == true)
|
||||||
.ToList();
|
.ToList(); // 转换为列表,避免多次枚举
|
||||||
|
|
||||||
// 将变量存储到字典中,方便以后通过ID快速查找
|
// 将变量存储到字典中,方便以后通过ID快速查找
|
||||||
foreach (var s7Variable in s7Variables)
|
foreach (var s7Variable in deviceS7Variables)
|
||||||
_variableDic[s7Variable.Id] = s7Variable;
|
_variableDic[s7Variable.Id] = s7Variable;
|
||||||
|
|
||||||
|
totalVariableCount += deviceS7Variables.Count; // 使用 Count 属性
|
||||||
varCount += s7Variables.Count();
|
_pollVariableDic.AddOrUpdate(device.Id, deviceS7Variables, (key, oldValue) => deviceS7Variables);
|
||||||
_pollVariableDic.Add(device.Id, s7Variables);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
NlogHelper.Info($"S7变量加载成功,共加载S7设备:{_s7Devices.Count}个,变量数:{varCount}");
|
NlogHelper.Info($"S7变量加载成功,共加载S7设备:{s7Devices.Count}个,变量数:{totalVariableCount}");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
NotificationHelper.ShowError($"S7后台服务加载变量时发生了错误:{e.Message}", e);
|
NotificationHelper.ShowError($"S7后台服务加载变量时发生了错误:{e.Message}", e);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 停止S7后台服务。
|
|
||||||
/// </summary>
|
|
||||||
public void StopService()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
NlogHelper.Info("S7后台服务正在关闭....");
|
|
||||||
_stopEvent.Set();
|
|
||||||
|
|
||||||
_pollingThread.Interrupt();
|
|
||||||
_serviceMainThread.Interrupt();
|
|
||||||
DisconnectAllPlc();
|
|
||||||
|
|
||||||
foreach (Device device in _deviceDic.Values.ToList())
|
|
||||||
{
|
|
||||||
device.IsRuning = false;
|
|
||||||
}
|
|
||||||
// 关闭事件
|
|
||||||
_reloadEvent.Close();
|
|
||||||
_stopEvent.Reset();
|
|
||||||
_stopEvent.Close();
|
|
||||||
// 清空所有字典。
|
|
||||||
_deviceDic.Clear();
|
|
||||||
_s7PlcClientDic.Clear();
|
|
||||||
_pollVariableDic.Clear();
|
|
||||||
NlogHelper.Info("S7后台服务已关闭");
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
NlogHelper.Error($"S7后台服务关闭时发生了错误:{e.Message}",e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 关闭所有PLC的连接
|
/// 关闭所有PLC的连接
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void DisconnectAllPlc()
|
private async Task DisconnectAllPlc()
|
||||||
{
|
{
|
||||||
if (_s7PlcClientDic==null || _s7PlcClientDic.Count == 0)
|
if (_s7PlcClientDic.IsEmpty)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
// 创建一个任务列表,用于并发关闭所有PLC连接
|
||||||
|
var closeTasks = new List<Task>();
|
||||||
|
|
||||||
// 关闭所有活跃的PLC连接。
|
// 关闭所有活跃的PLC连接。
|
||||||
foreach (var plcClient in _s7PlcClientDic.Values.ToList())
|
foreach (var plcClient in _s7PlcClientDic.Values)
|
||||||
{
|
{
|
||||||
try
|
if (plcClient.IsConnected)
|
||||||
{
|
{
|
||||||
if (plcClient.IsConnected)
|
closeTasks.Add(Task.Run(() =>
|
||||||
{
|
{
|
||||||
plcClient.Close();
|
try
|
||||||
NlogHelper.Info($"关闭S7连接: {plcClient.IP}");
|
{
|
||||||
}
|
plcClient.Close();
|
||||||
}
|
NlogHelper.Info($"关闭S7连接: {plcClient.IP}");
|
||||||
catch (Exception e)
|
}
|
||||||
{
|
catch (Exception e)
|
||||||
NlogHelper.Error($"S7后台服务关闭{plcClient.IP},后台连接时发生错误:{e.Message}",e);
|
{
|
||||||
|
NlogHelper.Error($"S7后台服务关闭{plcClient.IP},后台连接时发生错误:{e.Message}", e);
|
||||||
|
}
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 等待所有关闭任务完成
|
||||||
|
await Task.WhenAll(closeTasks);
|
||||||
|
_s7PlcClientDic.Clear(); // Clear the dictionary after all connections are attempted to be closed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,11 +143,11 @@ public partial class SettingViewModel : ViewModelBase
|
|||||||
_connectionSettings.Save();
|
_connectionSettings.Save();
|
||||||
if (value)
|
if (value)
|
||||||
{
|
{
|
||||||
_s7BackgroundService.StartService();
|
// _s7BackgroundService.StartService();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_s7BackgroundService.StopService();
|
// _s7BackgroundService.StopService();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user