将pollLevel属性名改为pollingInterval

This commit is contained in:
2025-09-05 20:24:27 +08:00
parent 6e123b47cc
commit 08f9de137e
17 changed files with 95 additions and 98 deletions

View File

@@ -16,7 +16,7 @@ public class VariableDto
public VariableTableDto? VariableTable { get; set; }
public List<VariableMqttAliasDto>? MqttAliases { get; set; }
public SignalType SignalType { get; set; }
public int PollLevel { get; set; }
public int PollingInterval { get; set; }
public bool IsActive { get; set; }
public int VariableTableId { get; set; }
public string OpcUaNodeId { get; set; }

View File

@@ -35,9 +35,9 @@ public class Variable
public SignalType SignalType { get; set; }
/// <summary>
/// 变量的轮询级别,决定了其读取频率。
/// 变量的轮询间隔(毫秒),决定了其读取频率。
/// </summary>
public int PollLevel { get; set; }
public int PollingInterval { get; set; }
/// <summary>
/// 指示此变量是否处于激活状态。

View File

@@ -147,7 +147,7 @@ namespace DMS.Infrastructure.UnitTests
.RuleFor(v => v.Name, f => f.Commerce.ProductName())
.RuleFor(v => v.S7Address, f => $"DB1.DBD{f.Random.Int(0, 1000)}")
.RuleFor(v => v.SignalType, f => f.PickRandom<SignalType>())
.RuleFor(v => v.PollLevel, f => f.Random.Int(10, 1800000))
.RuleFor(v => v.PollingInterval, f => f.Random.Int(10, 1800000))
.RuleFor(v => v.IsActive, f => f.Random.Bool())
.RuleFor(v => v.IsHistoryEnabled, f => f.Random.Bool())
.RuleFor(v => v.HistoryDeadband, f => f.Random.Double(0.0, 1.0))

View File

@@ -33,9 +33,9 @@ public class DbVariable
public SignalType SignalType { get; set; }
/// <summary>
/// 变量的轮询级别,决定数据采集频率。
/// 变量的轮询间隔(毫秒),决定数据采集频率。
/// </summary>
public int PollLevel { get; set; }
public int PollingInterval { get; set; }
/// <summary>
/// 指示此变量是否处于激活状态。

View File

@@ -263,7 +263,7 @@ public static class ExcelHelper
variable.OpcUaNodeId = "";
variable.Protocol = ProtocolType.S7;
variable.PollLevel = 30000; // ThirtySeconds
variable.PollingInterval = 30000; // ThirtySeconds
variableDatas.Add(variable);
}

View File

@@ -260,7 +260,7 @@ public class ExcelService : IExcelService
variable.OpcUaNodeId = "";
variable.Protocol = ProtocolType.S7;
variable.PollLevel = 30000; // ThirtySeconds
variable.PollingInterval = 30000; // ThirtySeconds
variableDatas.Add(variable);
}

View File

@@ -277,15 +277,15 @@ public class OpcUaBackgroundService : BackgroundService
if (_opcUaVariablesByDeviceId.TryGetValue(device.Id, out var opcUaVariables))
{
var variableGroup = opcUaVariables.GroupBy(variable => variable.PollLevel);
var variableGroup = opcUaVariables.GroupBy(variable => variable.PollingInterval);
foreach (var vGroup in variableGroup)
{
var pollLevel = vGroup.Key;
var pollingInterval = vGroup.Key;
var opcUaNodes
= vGroup.Select(variableDto => new OpcUaNode() { NodeId = variableDto.OpcUaNodeId })
.ToList();
PollingIntervals.TryGetValue(pollLevel, out var interval);
PollingIntervals.TryGetValue(pollingInterval, out var interval);
opcUaService.SubscribeToNode(opcUaNodes,HandleDataChanged,10000,1000);
}
}

View File

@@ -215,22 +215,22 @@ namespace DMS.Infrastructure.Services
_logger.LogInformation("正在为设备 {DeviceName} 设置订阅,变量数: {VariableCount}",
context.Device.Name, context.Variables.Count);
// 按PollLevel对变量进行分组
var variablesByPollLevel = context.Variables.Values
.GroupBy(v => v.PollLevel)
// 按PollingInterval对变量进行分组
var variablesByPollingInterval = context.Variables.Values
.GroupBy(v => v.PollingInterval)
.ToDictionary(g => g.Key, g => g.ToList());
// 为每个PollLevel组设置单独的订阅
foreach (var group in variablesByPollLevel)
// 为每个PollingInterval组设置单独的订阅
foreach (var group in variablesByPollingInterval)
{
int pollLevel = group.Key;
int pollingInterval = group.Key;
var variables = group.Value;
_logger.LogInformation("为设备 {DeviceName} 设置PollLevel {PollLevel} 的订阅,变量数: {VariableCount}",
context.Device.Name, pollLevel, variables.Count);
_logger.LogInformation("为设备 {DeviceName} 设置PollingInterval {PollingInterval} 的订阅,变量数: {VariableCount}",
context.Device.Name, pollingInterval, variables.Count);
// 根据PollLevel计算发布间隔和采样间隔毫秒
var publishingInterval = GetPublishingIntervalFromPollLevel(pollLevel);
// 根据PollingInterval计算发布间隔和采样间隔毫秒
var publishingInterval = GetPublishingIntervalFromPollLevel(pollingInterval);
// var samplingInterval = GetSamplingIntervalFromPollLevel(pollLevel);
var opcUaNodes = variables
@@ -251,12 +251,12 @@ namespace DMS.Infrastructure.Services
}
/// <summary>
/// 根据PollLevel获取发布间隔毫秒
/// 根据PollingInterval获取发布间隔毫秒
/// </summary>
private int GetPublishingIntervalFromPollLevel(int pollLevel)
private int GetPublishingIntervalFromPollLevel(int pollingInterval)
{
// 根据轮询级别值映射到发布间隔
return pollLevel switch
// 根据轮询间隔值映射到发布间隔
return pollingInterval switch
{
100 => 100, // HundredMilliseconds -> 100ms发布间隔
500 => 500, // FiveHundredMilliseconds -> 500ms发布间隔

View File

@@ -29,8 +29,8 @@ public class OptimizedS7BackgroundService : BackgroundService
// S7轮询一遍后的等待时间
private readonly int _s7PollOnceSleepTimeMs = 50;
// 存储每个设备的变量按轮询级别分组
private readonly ConcurrentDictionary<int, Dictionary<int, List<VariableDto>>> _variablesByPollLevel = new();
// 存储每个设备的变量按轮询间隔分组
private readonly ConcurrentDictionary<int, Dictionary<int, List<VariableDto>>> _variablesByPollingInterval = new();
// 模拟 PollingIntervals实际应用中可能从配置或数据库加载
private static readonly Dictionary<int, TimeSpan> PollingIntervals = new Dictionary<int, TimeSpan>
@@ -105,7 +105,7 @@ public class OptimizedS7BackgroundService : BackgroundService
// 持续轮询,直到取消请求或需要重新加载
while (!stoppingToken.IsCancellationRequested && _reloadSemaphore.CurrentCount == 0)
{
await PollS7VariablesByPollLevelAsync(stoppingToken);
await PollS7VariablesByPollingIntervalAsync(stoppingToken);
await Task.Delay(_s7PollOnceSleepTimeMs, stoppingToken);
}
}
@@ -131,7 +131,7 @@ public class OptimizedS7BackgroundService : BackgroundService
{
try
{
_variablesByPollLevel.Clear();
_variablesByPollingInterval.Clear();
_logger.LogInformation("开始加载S7变量....");
var s7Devices = _dataCenterService
@@ -149,12 +149,12 @@ public class OptimizedS7BackgroundService : BackgroundService
_s7ServiceManager.UpdateVariables(s7Device.Id, variables);
// 按轮询级别分组变量
var variablesByPollLevel = variables
.GroupBy(v => v.PollLevel)
// 按轮询间隔分组变量
var variablesByPollingInterval = variables
.GroupBy(v => v.PollingInterval)
.ToDictionary(g => g.Key, g => g.ToList());
_variablesByPollLevel.AddOrUpdate(s7Device.Id, variablesByPollLevel, (key, oldValue) => variablesByPollLevel);
_variablesByPollingInterval.AddOrUpdate(s7Device.Id, variablesByPollingInterval, (key, oldValue) => variablesByPollingInterval);
}
_logger.LogInformation($"S7 变量加载成功共加载S7设备{s7Devices.Count}个");
@@ -184,28 +184,28 @@ public class OptimizedS7BackgroundService : BackgroundService
}
/// <summary>
/// 按轮询级别轮询S7变量
/// 按轮询间隔轮询S7变量
/// </summary>
private async Task PollS7VariablesByPollLevelAsync(CancellationToken stoppingToken)
private async Task PollS7VariablesByPollingIntervalAsync(CancellationToken stoppingToken)
{
try
{
var pollTasks = new List<Task>();
// 为每个设备创建轮询任务
foreach (var deviceEntry in _variablesByPollLevel)
foreach (var deviceEntry in _variablesByPollingInterval)
{
var deviceId = deviceEntry.Key;
var variablesByPollLevel = deviceEntry.Value;
var variablesByPollingInterval = deviceEntry.Value;
// 为每个轮询级别创建轮询任务
foreach (var pollLevelEntry in variablesByPollLevel)
// 为每个轮询间隔创建轮询任务
foreach (var pollingIntervalEntry in variablesByPollingInterval)
{
var pollLevel = pollLevelEntry.Key;
var variables = pollLevelEntry.Value;
var pollingInterval = pollingIntervalEntry.Key;
var variables = pollingIntervalEntry.Value;
// 检查是否达到轮询时间
if (ShouldPollVariables(variables, pollLevel))
if (ShouldPollVariables(variables, pollingInterval))
{
pollTasks.Add(PollVariablesForDeviceAsync(deviceId, variables, stoppingToken));
}
@@ -216,16 +216,16 @@ public class OptimizedS7BackgroundService : BackgroundService
}
catch (Exception ex)
{
_logger.LogError(ex, $"按轮询级别轮询S7变量时发生错误{ex.Message}");
_logger.LogError(ex, $"按轮询间隔轮询S7变量时发生错误{ex.Message}");
}
}
/// <summary>
/// 检查是否应该轮询变量
/// </summary>
private bool ShouldPollVariables(List<VariableDto> variables, int pollLevel)
private bool ShouldPollVariables(List<VariableDto> variables, int pollingInterval)
{
if (!PollingIntervals.TryGetValue(pollLevel, out var interval))
if (!PollingIntervals.TryGetValue(pollingInterval, out var interval))
return false;
// 检查是否有任何一个变量需要轮询

View File

@@ -26,7 +26,7 @@ namespace DMS.Infrastructure.Services
private readonly ILogger<S7DeviceAgent> _logger;
private Plc _plc;
private bool _isConnected;
private readonly Dictionary<int, List<Variable>> _variablesByPollLevel;
private readonly Dictionary<int, List<Variable>> _variablesByPollingInterval;
private readonly Dictionary<int, DateTime> _lastPollTimes;
public S7DeviceAgent(Device device, IChannelBus channelBus, IMessenger messenger, ILogger<S7DeviceAgent> logger)
@@ -36,7 +36,7 @@ namespace DMS.Infrastructure.Services
_messenger = messenger ?? throw new ArgumentNullException(nameof(messenger));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_variablesByPollLevel = new Dictionary<int, List<Variable>>();
_variablesByPollingInterval = new Dictionary<int, List<Variable>>();
_lastPollTimes = new Dictionary<int, DateTime>();
InitializePlc();
@@ -125,18 +125,18 @@ namespace DMS.Infrastructure.Services
public void UpdateVariables(List<Variable> variables)
{
// 清空现有的变量分组
_variablesByPollLevel.Clear();
_variablesByPollingInterval.Clear();
_lastPollTimes.Clear();
// 按轮询级别分组变量
// 按轮询间隔分组变量
foreach (var variable in variables)
{
if (!_variablesByPollLevel.ContainsKey(variable.PollLevel))
if (!_variablesByPollingInterval.ContainsKey(variable.PollingInterval))
{
_variablesByPollLevel[variable.PollLevel] = new List<Variable>();
_lastPollTimes[variable.PollLevel] = DateTime.MinValue;
_variablesByPollingInterval[variable.PollingInterval] = new List<Variable>();
_lastPollTimes[variable.PollingInterval] = DateTime.MinValue;
}
_variablesByPollLevel[variable.PollLevel].Add(variable);
_variablesByPollingInterval[variable.PollingInterval].Add(variable);
}
_logger.LogInformation($"S7DeviceAgent: 更新设备 {_deviceConfig.Name} 的变量配置,共 {variables.Count} 个变量");
@@ -155,17 +155,17 @@ namespace DMS.Infrastructure.Services
try
{
// 按轮询级别依次轮询
foreach (var kvp in _variablesByPollLevel)
// 按轮询间隔依次轮询
foreach (var kvp in _variablesByPollingInterval)
{
var pollLevel = kvp.Key;
var pollingInterval = kvp.Key;
var variables = kvp.Value;
// 检查是否到了轮询时间
if (ShouldPoll(pollLevel))
if (ShouldPoll(pollingInterval))
{
await PollVariablesByLevelAsync(variables, pollLevel);
_lastPollTimes[pollLevel] = DateTime.Now;
await PollVariablesByLevelAsync(variables, pollingInterval);
_lastPollTimes[pollingInterval] = DateTime.Now;
}
}
}
@@ -175,23 +175,22 @@ namespace DMS.Infrastructure.Services
}
}
private bool ShouldPoll(int pollLevel)
private bool ShouldPoll(int PollingInterval)
{
// 获取轮询间隔
var interval = GetPollingInterval(pollLevel);
var interval = GetPollingInterval(PollingInterval);
// 检查是否到了轮询时间
if (_lastPollTimes.TryGetValue(pollLevel, out var lastPollTime))
if (_lastPollTimes.TryGetValue(PollingInterval, out var lastPollTime))
{
return DateTime.Now - lastPollTime >= interval;
}
return true;
}
private TimeSpan GetPollingInterval(int pollLevel)
private TimeSpan GetPollingInterval(int pollingInterval)
{
return pollLevel switch
return pollingInterval switch
{
10 => TimeSpan.FromMilliseconds(10), // TenMilliseconds
100 => TimeSpan.FromMilliseconds(100), // HundredMilliseconds
@@ -210,7 +209,7 @@ namespace DMS.Infrastructure.Services
};
}
private async Task PollVariablesByLevelAsync(List<Variable> variables, int pollLevel)
private async Task PollVariablesByLevelAsync(List<Variable> variables, int pollingInterval)
{
// 批量读取变量
var dataItems = new List<DataItem>();
@@ -259,7 +258,7 @@ namespace DMS.Infrastructure.Services
S7Address = variable.S7Address,
DataValue = variable.DataValue,
DisplayValue = variable.DisplayValue,
PollLevel = variable.PollLevel,
PollingInterval = variable.PollingInterval,
Protocol = variable.Protocol,
UpdatedAt = variable.UpdatedAt
// 可以根据需要添加其他属性
@@ -274,7 +273,7 @@ namespace DMS.Infrastructure.Services
}
}
_logger.LogDebug($"S7DeviceAgent: 设备 {_deviceConfig.Name} 完成 {pollLevel} 级别轮询,共处理 {dataItems.Count} 个变量");
_logger.LogDebug($"S7DeviceAgent: 设备 {_deviceConfig.Name} 完成 {pollingInterval} 毫秒轮询间隔,共处理 {dataItems.Count} 个变量");
}
catch (Exception ex)
{

View File

@@ -78,8 +78,6 @@
</Page>
<Page Update="Views\Dialogs\PollLevelDialog.xaml">
<Generator>MSBuild:Compile</Generator>
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
<Page Update="Views\Dialogs\ProcessingDialog.xaml">
<Generator>MSBuild:Compile</Generator>

View File

@@ -9,22 +9,22 @@ namespace DMS.WPF.ViewModels.Dialogs
public partial class PollLevelDialogViewModel : DialogViewModelBase<int?>
{
[ObservableProperty]
private int _selectedPollLevelType;
private int _selectedPollingInterval;
public List<int> PollLevelTypes { get; }
public List<int> PollingIntervals { get; }
public PollLevelDialogViewModel(int currentPollLevelType)
public PollLevelDialogViewModel(int currentPollingInterval)
{
PollLevelTypes = new List<int> { 10, 100, 500, 1000, 5000, 10000, 20000, 30000, 60000, 180000, 300000, 600000, 1800000, 3600000 };
SelectedPollLevelType = currentPollLevelType;
Title = "修改轮询频率";
PollingIntervals = new List<int> { 10, 100, 500, 1000, 5000, 10000, 20000, 30000, 60000, 180000, 300000, 600000, 1800000, 3600000 };
SelectedPollingInterval = currentPollingInterval;
Title = "修改轮询间隔";
PrimaryButText = "确定";
}
[RelayCommand]
private void PrimaryButton()
{
Close(SelectedPollLevelType);
Close(SelectedPollingInterval);
}
[RelayCommand]

View File

@@ -69,11 +69,11 @@ public partial class VariableItemViewModel : ObservableObject
private SignalType _signalType =SignalType.OtherASignal;
/// <summary>
/// 获取或设置变量的轮询等级
/// 用于决定数据采集的频率(如:高、中、低)
/// 获取或设置变量的轮询间隔(毫秒)
/// 用于决定数据采集的频率。
/// </summary>
[ObservableProperty]
private int _pollLevel = 30000; // ThirtySeconds
private int _pollingInterval = 30000; // ThirtySeconds
/// <summary>
/// 获取或设置一个值,该值指示此变量是否被激活。

View File

@@ -472,12 +472,12 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
/// </summary>
/// <param name="variablesToChange">要修改轮询频率的变量数据列表。</param>
[RelayCommand]
public async Task ChangePollLevel()
public async Task ChangePollingInterval()
{
// 检查是否有变量被选中
if (SelectedVariables.Count == 0)
{
_notificationService.ShowInfo("请选择要修改轮询频率的变量");
_notificationService.ShowInfo("请选择要修改轮询间隔的变量");
return;
}
@@ -485,16 +485,16 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
var validVariables = SelectedVariables.Cast<VariableItemViewModel>()
.ToList();
// 显示轮询频率选择对话框,并传入第一个变量的当前轮询频率作为默认值
// 显示轮询间隔选择对话框,并传入第一个变量的当前轮询间隔作为默认值
PollLevelDialogViewModel viewModel = new PollLevelDialogViewModel(validVariables.First()
.PollLevel);
var newPollLevelType = await _dialogService.ShowDialogAsync(viewModel);
if (newPollLevelType.HasValue)
.PollingInterval);
var newPollingInterval = await _dialogService.ShowDialogAsync(viewModel);
if (newPollingInterval.HasValue)
{
// 更新所有选定变量的轮询频率和修改状态
// 更新所有选定变量的轮询间隔和修改状态
foreach (var variable in validVariables)
{
variable.PollLevel = newPollLevelType.Value;
variable.PollingInterval = newPollingInterval.Value;
variable.UpdatedAt = DateTime.Now;
}
@@ -505,11 +505,11 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
if (result > 0)
{
// 显示成功通知
_notificationService.ShowSuccess($"已成功更新 {validVariables.Count} 个变量的轮询频率");
_notificationService.ShowSuccess($"已成功更新 {validVariables.Count} 个变量的轮询间隔");
}
else
{
_notificationService.ShowError("更新轮询频率失败");
_notificationService.ShowError("更新轮询间隔失败");
}
}
}

View File

@@ -20,8 +20,8 @@
<Grid>
<ComboBox
Margin="20"
ItemsSource="{Binding PollLevelTypes}"
SelectedItem="{Binding SelectedPollLevelType}">
ItemsSource="{Binding PollingIntervals}"
SelectedItem="{Binding SelectedPollingInterval}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />

View File

@@ -148,8 +148,8 @@
Grid.Row="2"
Grid.Column="0"
Margin="0,15,0,0"
hc:InfoElement.Title="轮询级别:"
Text="{Binding PollLevel}"
hc:InfoElement.Title="轮询间隔(毫秒):"
Text="{Binding PollingInterval}"
>
</hc:TextBox>

View File

@@ -179,9 +179,9 @@
</MenuItem.Icon>
</MenuItem>
<MenuItem
Command="{Binding ChangePollLevelCommand}"
Command="{Binding ChangePollingIntervalCommand}"
CommandParameter="{Binding PlacementTarget.SelectedItems, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
Header="修改轮询频率">
Header="修改轮询间隔">
<MenuItem.Icon>
<ui:FontIcon Icon="{x:Static ui:SegoeFluentIcons.Edit}" />
</MenuItem.Icon>
@@ -268,10 +268,10 @@
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="轮询频率" SortMemberPath="PollLevel">
<DataGridTemplateColumn Header="轮询间隔(毫秒)" SortMemberPath="PollingInterval">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PollLevel}" />
<TextBlock Text="{Binding PollingInterval}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>