Compare commits
3 Commits
f83c93fcf9
...
571bdbf258
| Author | SHA1 | Date | |
|---|---|---|---|
| 571bdbf258 | |||
| 4567f058b5 | |||
| 52edf16176 |
@@ -65,7 +65,7 @@ namespace ADP
|
||||
|
||||
//初始化数据库
|
||||
//DatabaseConfig.SetTenant(10001);
|
||||
//DatabaseConfig.InitMySql("127.0.0.1",3306,"ADP","root","123456");
|
||||
//DatabaseConfig.InitSqlite("127.0.0.1", 3306, "ADP", "root", "123456");
|
||||
//DatabaseConfig.CreateDatabaseAndCheckConnection(createDatabase: true, checkConnection: true);
|
||||
//SqlSugarContext.InitDatabase();
|
||||
//显示登录窗口
|
||||
|
||||
@@ -50,13 +50,11 @@ namespace ADP.ViewModels
|
||||
set => SetProperty(ref _IsLeftDrawerOpen, value);
|
||||
}
|
||||
|
||||
// 代理属性:动态反映当前被激活的 Scope 状态
|
||||
public TimeSpan RunningTime
|
||||
{
|
||||
get
|
||||
{
|
||||
if (CurrentContext == null) return TimeSpan.Zero;
|
||||
// 💡 核心:如果当前工位的计时器正在跑,动态累加 SW 当前的时间,否则返回其保存的固定时间值
|
||||
return CurrentContext.SW.IsRunning ? CurrentContext.SW.Elapsed : CurrentContext.RunningTime;
|
||||
}
|
||||
set
|
||||
|
||||
19
Common/Attributes/MonitorableAttribute.cs
Normal file
19
Common/Attributes/MonitorableAttribute.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Common.Attributes
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
|
||||
public class MonitorableAttribute : Attribute
|
||||
{
|
||||
public string? Description { get; set; }
|
||||
|
||||
public MonitorableAttribute(string? description = null)
|
||||
{
|
||||
Description = description;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 查询通道实时测得的电压有效值(RMS,支持 AC 或 DC 模式下的回测)(单位: V)
|
||||
/// </summary>
|
||||
[Monitorable("交流电源电压")]
|
||||
public virtual async Task<string> 查询实际电压(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:VOLTage?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -154,6 +155,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 查询通道实时测得的电流有效值(RMS)(单位: A)
|
||||
/// </summary>
|
||||
[Monitorable("交流电源电流")]
|
||||
public virtual async Task<string> 查询实际电流(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:CURRent?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -162,6 +164,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 查询通道实时测得的有功功率值 (单位: W)
|
||||
/// </summary>
|
||||
[Monitorable("交流电源功率")]
|
||||
public virtual async Task<string> 查询实际功率(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:POWer?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
|
||||
@@ -226,6 +226,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 3.4.1. 回读通道输出端子上的实时测得电压值 (单位: V)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流电源电压")]
|
||||
public virtual async Task<string> 查询实际电压(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($"MEASure:VOLTage?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -234,6 +235,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 3.4.2. 回读通道输出端子上的实时测得电流值 (单位: A)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流电源电流")]
|
||||
public virtual async Task<string> 查询实际电流(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($"MEASure:CURRent?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -242,6 +244,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 3.4.3. 回读通道输出端子上的实时测得功率值 (单位: W)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流电源功率")]
|
||||
public virtual async Task<string> 查询实际功率(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($"MEASure:POWer?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
|
||||
@@ -191,6 +191,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 3.5.1 查询通道输出端子上测得的直流电流值 (A)
|
||||
/// </summary>
|
||||
[Monitorable("低压直流电源电流")]
|
||||
public virtual async Task<string> 查询实际电流(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:CURRent?{SCPIDelimiter}", SCPIDelimiter, ct);
|
||||
@@ -199,6 +200,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 3.5.2 查询通道输出端子上测得的直流功率值 (W)
|
||||
/// </summary>
|
||||
[Monitorable("低压直流电源功率")]
|
||||
public virtual async Task<string> 查询实际功率(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:POWer?{SCPIDelimiter}", SCPIDelimiter, ct);
|
||||
@@ -206,7 +208,8 @@ namespace DeviceCommand.Device
|
||||
|
||||
/// <summary>
|
||||
/// 3.5.3 查询通道输出端子上测得的直流电压值 (V)
|
||||
/// </summary>
|
||||
/// </summary
|
||||
[Monitorable("低压直流电源电压")]
|
||||
public virtual async Task<string> 查询实际电压(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:VOLTage?{SCPIDelimiter}", SCPIDelimiter, ct);
|
||||
|
||||
@@ -193,6 +193,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 回读电子负载输入端子上的实时测得电压值 (单位: V)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流负载电压")]
|
||||
public virtual async Task<string> 查询实际电压(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:VOLTage?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -201,6 +202,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 回读电子负载输入端子上的实时测得电流值 (单位: A)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流负载电流")]
|
||||
public virtual async Task<string> 查询实际电流(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:CURRent?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
@@ -209,6 +211,7 @@ namespace DeviceCommand.Device
|
||||
/// <summary>
|
||||
/// 回读电子负载输入端子上的实时测得功率值 (单位: W)
|
||||
/// </summary>
|
||||
[Monitorable("高压直流负载功率")]
|
||||
public virtual async Task<string> 查询实际功率(CancellationToken ct = default)
|
||||
{
|
||||
return await WriteReadAsync($":MEASure:POWer?{ScpiDelimiter}", ScpiDelimiter, ct);
|
||||
|
||||
14
Model/Entity/MonitorValueEntity.cs
Normal file
14
Model/Entity/MonitorValueEntity.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Model.Entity
|
||||
{
|
||||
public class MonitorValueEntity:BaseEntity
|
||||
{
|
||||
public string MonitorName;
|
||||
public double MonitorValue;
|
||||
}
|
||||
}
|
||||
21
Model/Models/AvailableMethodItem.cs
Normal file
21
Model/Models/AvailableMethodItem.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Model.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 可用设备方法项(供用户选择添加为监测通道)
|
||||
/// </summary>
|
||||
public class AvailableMethodItem
|
||||
{
|
||||
public string DeviceName { get; set; } = string.Empty;
|
||||
public string MethodName { get; set; } = string.Empty;
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public MethodInfo MethodInfo { get; set; } = null!;
|
||||
public object Device { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
91
MonitorModule/ViewModels/MonitorChannel.cs
Normal file
91
MonitorModule/ViewModels/MonitorChannel.cs
Normal file
@@ -0,0 +1,91 @@
|
||||
using OxyPlot.Series;
|
||||
using OxyPlot;
|
||||
using System.Collections.Concurrent;
|
||||
using Prism.Mvvm;
|
||||
using NCalc;
|
||||
|
||||
namespace MonitorModule.ViewModels
|
||||
{
|
||||
/// <summary>
|
||||
/// 监测通道:一个设备方法对应一个通道。
|
||||
/// 数据记录(DataPoints)与图表显示(Series)完全分离:
|
||||
/// - IsMonitored=true 时始终记录 DataPoints
|
||||
/// - IsDisplayed=true 时才创建 LineSeries 并绘制
|
||||
/// </summary>
|
||||
public class MonitorChannel : BindableBase
|
||||
{
|
||||
// ===== 标识 =====
|
||||
public string DeviceName { get; init; } = string.Empty;
|
||||
public string MethodName { get; init; } = string.Empty;
|
||||
public string DisplayName { get; init; } = string.Empty;
|
||||
|
||||
// ===== 状态 =====
|
||||
private bool _isMonitored = true;
|
||||
/// <summary>是否在记录数据点(添加后始终为 true)</summary>
|
||||
public bool IsMonitored
|
||||
{
|
||||
get => _isMonitored;
|
||||
set => SetProperty(ref _isMonitored, value);
|
||||
}
|
||||
|
||||
private bool _isDisplayed = true;
|
||||
/// <summary>是否在 OxyPlot 上显示</summary>
|
||||
public bool IsDisplayed
|
||||
{
|
||||
get => _isDisplayed;
|
||||
set => SetProperty(ref _isDisplayed, value);
|
||||
}
|
||||
|
||||
// ===== 数学变换 =====
|
||||
private string? _mathExpression;
|
||||
/// <summary>可选数学变换表达式,如 "x*0.001"。为空则 DisplayValue=RawValue</summary>
|
||||
public string? MathExpression
|
||||
{
|
||||
get => _mathExpression;
|
||||
set => SetProperty(ref _mathExpression, value);
|
||||
}
|
||||
|
||||
// ===== 颜色 =====
|
||||
public OxyColor Color { get; set; } = OxyColors.SteelBlue;
|
||||
|
||||
// ===== 数据存储 =====
|
||||
/// <summary>所有采样数据点(线程安全),与 OxyPlot 无关</summary>
|
||||
public ConcurrentQueue<(double Time, double RawValue, double DisplayValue)> DataPoints { get; } = new();
|
||||
|
||||
/// <summary>最大缓冲数据点数,超出则丢弃最旧的</summary>
|
||||
public int MaxBuffer { get; set; } = 5000;
|
||||
|
||||
// ===== OxyPlot Series(仅 IsDisplayed=true 时存在)=====
|
||||
private LineSeries? _series;
|
||||
public LineSeries? Series
|
||||
{
|
||||
get => _series;
|
||||
set => SetProperty(ref _series, value);
|
||||
}
|
||||
|
||||
// ===== 辅助方法 =====
|
||||
/// <summary>记录一个数据点:RawValue 经数学变换后得到 DisplayValue,一并入队</summary>
|
||||
public void Record(double time, double rawValue)
|
||||
{
|
||||
double displayValue = rawValue;
|
||||
|
||||
DataPoints.Enqueue((time, rawValue, displayValue));
|
||||
|
||||
// 超出缓冲上限时批量丢弃旧数据
|
||||
while (DataPoints.Count > MaxBuffer)
|
||||
{
|
||||
DataPoints.TryDequeue(out _);
|
||||
}
|
||||
|
||||
// 如果正在显示,同步到 Series
|
||||
if (_series != null)
|
||||
{
|
||||
_series.Points.Add(new DataPoint(time, displayValue));
|
||||
while (_series.Points.Count > 200)
|
||||
{
|
||||
_series.Points.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,31 @@
|
||||
using OxyPlot;
|
||||
using Common.Attributes;
|
||||
using Model.Entity;
|
||||
using Model.Models;
|
||||
using OxyPlot;
|
||||
using OxyPlot.Axes;
|
||||
using OxyPlot.Legends;
|
||||
using OxyPlot.Series;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using UIShare.GlobalVariable;
|
||||
using UIShare.PubEvent;
|
||||
using UIShare.ViewModelBase;
|
||||
|
||||
|
||||
namespace MonitorModule.ViewModels
|
||||
{
|
||||
/// <summary>
|
||||
/// 监控界面 VM —— 基于 OxyPlot 的曲线监控壳。
|
||||
/// 当前阶段不接入真实数据源,仅搭好框架:
|
||||
/// - 添加信号 / 删除信号
|
||||
/// - 重置视图(按数据范围复原)
|
||||
/// - 刷新(重绘 PlotView)
|
||||
/// 仍延续 ScopedContext 隔离 + 双击展开 的范式,每个工位独立一份图表与信号列表。
|
||||
/// </summary>
|
||||
public class MonitorViewModel : NavigateViewModelBase, IRegionMemberLifetime, IDisposable
|
||||
{
|
||||
#region 属性
|
||||
public bool KeepAlive => true;
|
||||
public ScopedContext _scopedContext { get; set; }
|
||||
public ScopedContext _scopedContext { get; set; } = null!;
|
||||
public GlobalInfo _globalInfo { get; set; }
|
||||
|
||||
public string TestStatus
|
||||
@@ -32,16 +34,26 @@ namespace MonitorModule.ViewModels
|
||||
set => SetProperty(ref _testStatus, value);
|
||||
}
|
||||
|
||||
/// <summary>PlotView 直接绑这个 PlotModel</summary>
|
||||
public PlotModel Plot { get; }
|
||||
|
||||
/// <summary>当前已添加的信号集合(左侧列表展示)</summary>
|
||||
public ObservableCollection<SignalItem> Signals { get; } = new();
|
||||
/// <summary>已添加的监测通道列表</summary>
|
||||
public ObservableCollection<MonitorChannel> Channels { get; } = new();
|
||||
|
||||
public SignalItem? SelectedSignal
|
||||
/// <summary>可添加的设备方法列表(供用户选择)</summary>
|
||||
public ObservableCollection<AvailableMethodItem> AvailableMethods { get; } = new();
|
||||
|
||||
private MonitorChannel? _selectedChannel;
|
||||
public MonitorChannel? SelectedChannel
|
||||
{
|
||||
get => _selectedSignal;
|
||||
set => SetProperty(ref _selectedSignal, value);
|
||||
get => _selectedChannel;
|
||||
set => SetProperty(ref _selectedChannel, value);
|
||||
}
|
||||
|
||||
private AvailableMethodItem? _selectedAvailableMethod;
|
||||
public AvailableMethodItem? SelectedAvailableMethod
|
||||
{
|
||||
get => _selectedAvailableMethod;
|
||||
set => SetProperty(ref _selectedAvailableMethod, value);
|
||||
}
|
||||
|
||||
public string StatusMessage
|
||||
@@ -50,67 +62,71 @@ namespace MonitorModule.ViewModels
|
||||
set => SetProperty(ref _statusMessage, value);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 命令
|
||||
public ICommand AddSignalCommand { get; }
|
||||
public ICommand DeleteSignalCommand { get; }
|
||||
public ICommand AddChannelCommand { get; }
|
||||
public ICommand DeleteChannelCommand { get; }
|
||||
public ICommand ResetViewCommand { get; }
|
||||
public ICommand RefreshDataCommand { get; }
|
||||
// 双击展开/折叠:与 RecordView/AutomatedTestingView 共用同一套 ExpandViewEvent
|
||||
public ICommand RefreshCommand { get; }
|
||||
#endregion
|
||||
|
||||
#region 私有字段
|
||||
private bool IsInitiated = false;
|
||||
private IScopedProvider _scope;
|
||||
// 颜色轮转池,给新加的信号自动分配区分色
|
||||
private IScopedProvider? _scope;
|
||||
private DeviceManager? _deviceManager;
|
||||
private CancellationTokenSource? _monitorCTS = new();
|
||||
|
||||
private static readonly OxyColor[] _palette =
|
||||
{
|
||||
OxyColors.SteelBlue, OxyColors.IndianRed, OxyColors.SeaGreen,
|
||||
OxyColors.DarkOrange, OxyColors.MediumPurple, OxyColors.Goldenrod,
|
||||
OxyColors.Teal, OxyColors.Crimson, OxyColors.OliveDrab
|
||||
};
|
||||
private int _signalCounter;
|
||||
OxyColors.SteelBlue, OxyColors.IndianRed, OxyColors.SeaGreen,
|
||||
OxyColors.DarkOrange, OxyColors.MediumPurple, OxyColors.Goldenrod,
|
||||
OxyColors.Teal, OxyColors.Crimson, OxyColors.OliveDrab
|
||||
};
|
||||
private int _colorIndex;
|
||||
|
||||
// ===== 模拟数据相关 =====
|
||||
// 模拟定时器:周期性给每条信号追加新点,形成滚动效果
|
||||
private readonly DispatcherTimer _simTimer;
|
||||
// 全局采样时间(秒),每 tick 自增 _simInterval
|
||||
private double _simT;
|
||||
// 采样间隔(秒),与 DispatcherTimer.Interval 保持一致
|
||||
private const double _simInterval = 0.1;
|
||||
// 滚动窗口大小:每条曲线最多保留 200 个点(约 20 秒)
|
||||
private const int _maxPoints = 200;
|
||||
// 用于 random walk 的随机源
|
||||
private static readonly Random _rng = new();
|
||||
private readonly DispatcherTimer _sampleTimer;
|
||||
private double _sampleTime;
|
||||
private const double _sampleInterval = 0.1; // 100ms
|
||||
private string _testStatus = string.Empty;
|
||||
private SignalItem? _selectedSignal;
|
||||
private string _statusMessage = "图表已就绪,暂无信号";
|
||||
private string _statusMessage = "图表已就绪,暂无监测项";
|
||||
|
||||
/// <summary>反射方法缓存:Channel → (MethodInfo, DeviceInstance)</summary>
|
||||
private readonly Dictionary<MonitorChannel, (MethodInfo Method, object Device)> _methodCache = new();
|
||||
#endregion
|
||||
|
||||
public MonitorViewModel(IContainerExtension container) : base(container)
|
||||
{
|
||||
_globalInfo = container.Resolve<GlobalInfo>();
|
||||
Plot = BuildEmptyPlot();
|
||||
AddSignalCommand = new DelegateCommand(OnAddSignal);
|
||||
DeleteSignalCommand = new DelegateCommand(OnDeleteSignal);
|
||||
AddChannelCommand = new DelegateCommand(OnAddChannel);
|
||||
DeleteChannelCommand = new DelegateCommand(OnDeleteChannel);
|
||||
ResetViewCommand = new DelegateCommand(OnResetView);
|
||||
RefreshDataCommand = new DelegateCommand(OnRefreshData);
|
||||
RefreshCommand = new DelegateCommand(OnExpand);
|
||||
|
||||
// 启动模拟数据定时器:100ms 一帧,给每条信号喂一个新点
|
||||
_simTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(_simInterval) };
|
||||
_simTimer.Tick += OnSimTick;
|
||||
_simTimer.Start();
|
||||
|
||||
// 默认预置 3 条模拟信号,便于直接看到滚动效果
|
||||
OnAddSignal(); // sin
|
||||
OnAddSignal(); // cos
|
||||
OnAddSignal(); // random walk
|
||||
_sampleTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(_sampleInterval) };
|
||||
_sampleTimer.Tick += OnSampleTick;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_simTimer?.Stop();
|
||||
// 1. 率先掐断后台正在并行的所有硬件请求
|
||||
_monitorCTS?.Cancel();
|
||||
_monitorCTS?.Dispose();
|
||||
_monitorCTS = null;
|
||||
|
||||
// 2. 停掉定时器,停止触发 UI 刷新
|
||||
_sampleTimer?.Stop();
|
||||
_sampleTimer.Tick -= OnSampleTick;
|
||||
|
||||
// 3. 释放容器作用域
|
||||
_scope?.Dispose();
|
||||
|
||||
// 4. 清理集合
|
||||
Channels.Clear();
|
||||
AvailableMethods.Clear();
|
||||
_methodCache.Clear();
|
||||
}
|
||||
|
||||
#region PlotModel 构建
|
||||
@@ -125,14 +141,14 @@ namespace MonitorModule.ViewModels
|
||||
pm.Axes.Add(new LinearAxis
|
||||
{
|
||||
Position = AxisPosition.Bottom,
|
||||
Title = "X",
|
||||
Title = "时间 (s)",
|
||||
MajorGridlineStyle = LineStyle.Dot,
|
||||
MinorGridlineStyle = LineStyle.None
|
||||
});
|
||||
pm.Axes.Add(new LinearAxis
|
||||
{
|
||||
Position = AxisPosition.Left,
|
||||
Title = "Y",
|
||||
Title = "值",
|
||||
MajorGridlineStyle = LineStyle.Dot,
|
||||
MinorGridlineStyle = LineStyle.None
|
||||
});
|
||||
@@ -146,92 +162,136 @@ namespace MonitorModule.ViewModels
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 命令处理
|
||||
/// <summary>
|
||||
/// 添加一条信号:按 _signalCounter 轮转选择不同波形 generator,
|
||||
/// 后续 _simTimer 每帧会调用 generator(t) 给曲线追加新点形成滚动效果。
|
||||
/// </summary>
|
||||
private void OnAddSignal()
|
||||
#region 设备方法发现
|
||||
private void DiscoverAvailableMethods()
|
||||
{
|
||||
_signalCounter++;
|
||||
var color = _palette[(_signalCounter - 1) % _palette.Length];
|
||||
|
||||
// 6 种波形轮转:sin / cos / 锯齿 / 方波 / 衰减正弦 / random walk
|
||||
var (waveName, generator) = BuildGenerator(_signalCounter);
|
||||
var name = $"{waveName}_{_signalCounter}";
|
||||
|
||||
var series = new LineSeries
|
||||
AvailableMethods.Clear();
|
||||
if (_deviceManager?.DeviceMap == null || _deviceManager.DeviceMap.Count == 0)
|
||||
{
|
||||
Title = name,
|
||||
Color = color,
|
||||
StrokeThickness = 1.5
|
||||
};
|
||||
|
||||
var item = new SignalItem(name, series, generator);
|
||||
Signals.Add(item);
|
||||
SelectedSignal = item;
|
||||
|
||||
Plot.Series.Add(series);
|
||||
Plot.InvalidatePlot(true);
|
||||
|
||||
StatusMessage = $"已添加信号 [{name}],当前共 {Signals.Count} 条";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按索引返回一种模拟波形发生器。
|
||||
/// 振幅 / 频率 / 相位都做了区分,让多条曲线视觉上分开。
|
||||
/// </summary>
|
||||
private static (string waveName, Func<double, double> generator) BuildGenerator(int index)
|
||||
{
|
||||
// 给同种波形不同实例一些随机偏移,避免完全重叠
|
||||
double phase = (index * 0.7) % (2 * Math.PI);
|
||||
double amp = 1.0 + (index % 3) * 0.3;
|
||||
double freq = 0.5 + (index % 4) * 0.2;
|
||||
|
||||
return (index % 6) switch
|
||||
{
|
||||
0 => ("Sin", t => amp * Math.Sin(2 * Math.PI * freq * t + phase)),
|
||||
1 => ("Cos", t => amp * Math.Cos(2 * Math.PI * freq * t + phase)),
|
||||
2 => ("Saw", t => amp * (2 * ((t * freq) - Math.Floor(t * freq + 0.5)))),
|
||||
3 => ("Square", t => amp * Math.Sign(Math.Sin(2 * Math.PI * freq * t + phase))),
|
||||
4 => ("Decay", t => amp * Math.Exp(-0.05 * t) * Math.Sin(2 * Math.PI * freq * t + phase)),
|
||||
_ => RandomWalkGenerator(amp),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>构造一个随机游走 generator:在前一次值基础上叠加高斯噪声。</summary>
|
||||
private static (string, Func<double, double>) RandomWalkGenerator(double amp)
|
||||
{
|
||||
double last = 0;
|
||||
return ("Walk", _ =>
|
||||
{
|
||||
last += (_rng.NextDouble() - 0.5) * 0.2 * amp;
|
||||
// 软约束在 [-amp*3, amp*3],避免一直跑偏
|
||||
if (last > amp * 3) last = amp * 3;
|
||||
if (last < -amp * 3) last = -amp * 3;
|
||||
return last;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>删除当前选中信号;若未选中则删除最后一条。</summary>
|
||||
private void OnDeleteSignal()
|
||||
{
|
||||
var target = SelectedSignal ?? Signals.LastOrDefault();
|
||||
if (target == null)
|
||||
{
|
||||
StatusMessage = "无可删除的信号";
|
||||
StatusMessage = "当前工位无可用设备";
|
||||
return;
|
||||
}
|
||||
|
||||
Plot.Series.Remove(target.Series);
|
||||
Signals.Remove(target);
|
||||
SelectedSignal = Signals.LastOrDefault();
|
||||
foreach (var kvp in _deviceManager.DeviceMap)
|
||||
{
|
||||
string deviceName = kvp.Key;
|
||||
var device = kvp.Value;
|
||||
var deviceType = device.GetType();
|
||||
|
||||
// 改用特性过滤:仅扫描带有 [Monitorable] 特性且签名正确的方法
|
||||
var methods = deviceType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(m =>
|
||||
{
|
||||
var attribute = m.GetCustomAttribute<MonitorableAttribute>();
|
||||
if (attribute == null) return false;
|
||||
|
||||
if (m.ReturnType != typeof(Task<string>)) return false;
|
||||
|
||||
var parms = m.GetParameters();
|
||||
bool validParams = parms.Length == 0 ||
|
||||
(parms.Length == 1 && parms[0].ParameterType == typeof(CancellationToken));
|
||||
|
||||
return validParams;
|
||||
});
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var attr = method.GetCustomAttribute<MonitorableAttribute>();
|
||||
string displayName = !string.IsNullOrEmpty(attr?.Description)
|
||||
? $"{deviceName}.{attr.Description}"
|
||||
: $"{deviceName}.{method.Name}";
|
||||
|
||||
var item = new AvailableMethodItem
|
||||
{
|
||||
DeviceName = deviceName,
|
||||
MethodName = method.Name,
|
||||
DisplayName = displayName,
|
||||
MethodInfo = method,
|
||||
Device = device
|
||||
};
|
||||
AvailableMethods.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
StatusMessage = AvailableMethods.Count > 0
|
||||
? $"发现 {AvailableMethods.Count} 个可监测项"
|
||||
: "未发现可监测的设备方法";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 命令处理
|
||||
private void OnAddChannel()
|
||||
{
|
||||
var method = SelectedAvailableMethod;
|
||||
if (method == null)
|
||||
{
|
||||
StatusMessage = "请先在列表中选择一个监测项";
|
||||
return;
|
||||
}
|
||||
|
||||
if (Channels.Any(c => c.DeviceName == method.DeviceName && c.MethodName == method.MethodName))
|
||||
{
|
||||
StatusMessage = $"监测项 [{method.DisplayName}] 已存在";
|
||||
return;
|
||||
}
|
||||
|
||||
var color = _palette[_colorIndex % _palette.Length];
|
||||
_colorIndex++;
|
||||
|
||||
var channel = new MonitorChannel
|
||||
{
|
||||
DeviceName = method.DeviceName,
|
||||
MethodName = method.MethodName,
|
||||
DisplayName = method.DisplayName,
|
||||
Color = color,
|
||||
IsMonitored = true,
|
||||
IsDisplayed = true
|
||||
};
|
||||
|
||||
channel.Series = new LineSeries
|
||||
{
|
||||
Title = channel.DisplayName,
|
||||
Color = color,
|
||||
StrokeThickness = 1.5
|
||||
};
|
||||
Plot.Series.Add(channel.Series);
|
||||
|
||||
_methodCache[channel] = (method.MethodInfo, method.Device);
|
||||
|
||||
channel.PropertyChanged += (s, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(MonitorChannel.IsDisplayed))
|
||||
OnChannelDisplayChanged(channel);
|
||||
};
|
||||
|
||||
Channels.Add(channel);
|
||||
SelectedChannel = channel;
|
||||
|
||||
Plot.InvalidatePlot(true);
|
||||
StatusMessage = $"已删除信号 [{target.Name}],剩余 {Signals.Count} 条";
|
||||
StatusMessage = $"已添加监测项 [{channel.DisplayName}],当前共 {Channels.Count} 项";
|
||||
}
|
||||
|
||||
private void OnDeleteChannel()
|
||||
{
|
||||
var target = SelectedChannel ?? Channels.LastOrDefault();
|
||||
if (target == null)
|
||||
{
|
||||
StatusMessage = "无可删除的监测项";
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.Series != null)
|
||||
{
|
||||
Plot.Series.Remove(target.Series);
|
||||
}
|
||||
_methodCache.Remove(target);
|
||||
Channels.Remove(target);
|
||||
SelectedChannel = Channels.LastOrDefault();
|
||||
|
||||
Plot.InvalidatePlot(true);
|
||||
StatusMessage = $"已删除监测项 [{target.DisplayName}],剩余 {Channels.Count} 项";
|
||||
}
|
||||
|
||||
/// <summary>按数据范围复原视图(重置所有坐标轴的缩放/平移)。</summary>
|
||||
private void OnResetView()
|
||||
{
|
||||
Plot.ResetAllAxes();
|
||||
@@ -239,52 +299,144 @@ namespace MonitorModule.ViewModels
|
||||
StatusMessage = "视图已按数据范围复原";
|
||||
}
|
||||
|
||||
/// <summary>刷新:触发 PlotView 重绘;后续接数据源时可在此重拉数据。</summary>
|
||||
private void OnRefreshData()
|
||||
{
|
||||
Plot.InvalidatePlot(true);
|
||||
StatusMessage = $"已刷新({DateTime.Now:HH:mm:ss})";
|
||||
}
|
||||
|
||||
/// <summary>双击展开 / 折叠九宫格。</summary>
|
||||
private void OnExpand()
|
||||
{
|
||||
if (string.IsNullOrEmpty(TestStatus)) return;
|
||||
_globalInfo.CurrentScope = TestStatus;
|
||||
_eventAggregator.GetEvent<ExpandViewEvent>().Publish(TestStatus);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 显示/隐藏切换与数学变换
|
||||
public void OnChannelDisplayChanged(MonitorChannel channel)
|
||||
{
|
||||
if (channel.IsDisplayed)
|
||||
{
|
||||
if (channel.Series == null)
|
||||
{
|
||||
channel.Series = new LineSeries
|
||||
{
|
||||
Title = channel.DisplayName,
|
||||
Color = channel.Color,
|
||||
StrokeThickness = 1.5
|
||||
};
|
||||
|
||||
var recent = channel.DataPoints.ToArray();
|
||||
var startIdx = Math.Max(0, recent.Length - 200);
|
||||
for (int i = startIdx; i < recent.Length; i++)
|
||||
{
|
||||
channel.Series.Points.Add(new DataPoint(recent[i].Time, recent[i].DisplayValue));
|
||||
}
|
||||
|
||||
Plot.Series.Add(channel.Series);
|
||||
Plot.InvalidatePlot(true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (channel.Series != null)
|
||||
{
|
||||
Plot.Series.Remove(channel.Series);
|
||||
channel.Series = null;
|
||||
Plot.InvalidatePlot(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟数据 tick:每条信号按当前 _simT 算出新点并追加。
|
||||
/// 超过 _maxPoints 时丢弃最旧的点形成滚动窗口。
|
||||
/// </summary>
|
||||
private void OnSimTick(object? sender, EventArgs e)
|
||||
public void OnChannelMathChanged(MonitorChannel channel)
|
||||
{
|
||||
_simT += _simInterval;
|
||||
if (channel.Series == null) return;
|
||||
|
||||
if (Signals.Count == 0)
|
||||
var points = channel.DataPoints.ToArray();
|
||||
channel.Series.Points.Clear();
|
||||
var startIdx = Math.Max(0, points.Length - 200);
|
||||
for (int i = startIdx; i < points.Length; i++)
|
||||
{
|
||||
return;
|
||||
channel.Series.Points.Add(new DataPoint(points[i].Time, points[i].DisplayValue));
|
||||
}
|
||||
Plot.InvalidatePlot(true);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 采样定时器与高并发处理
|
||||
private async void OnSampleTick(object? sender, EventArgs e)
|
||||
{
|
||||
_sampleTime += _sampleInterval;
|
||||
|
||||
if (Channels.Count == 0 || _methodCache.Count == 0) return;
|
||||
|
||||
var sampleTasks = new List<Task>();
|
||||
var token = _monitorCTS?.Token ?? CancellationToken.None;
|
||||
|
||||
// 1. 并行发起所有通道的数据采集,防止单一通道硬件断连卡死全局采样
|
||||
foreach (var channel in Channels)
|
||||
{
|
||||
if (!channel.IsMonitored) continue;
|
||||
if (!_methodCache.TryGetValue(channel, out var entry)) continue;
|
||||
|
||||
sampleTasks.Add(Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var (method, device) = entry;
|
||||
|
||||
// 动态分析方法签名准备反射参数
|
||||
var parmsInfo = method.GetParameters();
|
||||
object?[]? invokeArgs = parmsInfo.Length == 1 && parmsInfo[0].ParameterType == typeof(CancellationToken)
|
||||
? new object[] { token }
|
||||
: null;
|
||||
|
||||
if (method.Invoke(device, invokeArgs) is Task<string> task)
|
||||
{
|
||||
string raw = await task.ConfigureAwait(false);
|
||||
|
||||
if (double.TryParse(raw, out double value))
|
||||
{
|
||||
channel.Record(_sampleTime, value);
|
||||
var entity = new MonitorValueEntity
|
||||
{
|
||||
MonitorName = channel.DisplayName,
|
||||
MonitorValue = value,
|
||||
CreateTime = DateTime.Now,
|
||||
IsDel = 0
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 某个硬件通道故障时不干扰其他通道
|
||||
}
|
||||
}, token));
|
||||
}
|
||||
|
||||
foreach (var item in Signals)
|
||||
// 2. 批量等待并发采样,加入 2 秒强制超时保护兜底
|
||||
if (sampleTasks.Count > 0)
|
||||
{
|
||||
double y = item.Generator(_simT);
|
||||
item.Series.Points.Add(new DataPoint(_simT, y));
|
||||
if (item.Series.Points.Count > _maxPoints)
|
||||
try
|
||||
{
|
||||
item.Series.Points.RemoveAt(0);
|
||||
var delayTask = Task.Delay(TimeSpan.FromSeconds(2), token);
|
||||
await Task.WhenAny(Task.WhenAll(sampleTasks), delayTask).ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 让 X 轴跟着最新数据滚动
|
||||
// 3. 【回归UI线程】由于前面 ConfigureAwait(true),这里直接执行 OxyPlot 坐标滚动与刷新
|
||||
var xAxis = Plot.Axes.FirstOrDefault(a => a.Position == AxisPosition.Bottom);
|
||||
if (xAxis != null)
|
||||
{
|
||||
double window = _maxPoints * _simInterval;
|
||||
xAxis.Minimum = Math.Max(0, _simT - window);
|
||||
xAxis.Maximum = _simT + 0.5;
|
||||
double window = 200 * _sampleInterval;
|
||||
xAxis.Minimum = Math.Max(0, _sampleTime - window);
|
||||
xAxis.Maximum = _sampleTime + 0.5;
|
||||
}
|
||||
|
||||
Plot.InvalidatePlot(true);
|
||||
@@ -302,26 +454,19 @@ namespace MonitorModule.ViewModels
|
||||
Plot.InvalidatePlot(false);
|
||||
_scope = _globalInfo.ScopeDic[TestStatus];
|
||||
_scopedContext = _scope.Resolve<ScopedContext>();
|
||||
_deviceManager = _scope.Resolve<DeviceManager>();
|
||||
IsInitiated = true;
|
||||
|
||||
// 初始化全新的取消信号源
|
||||
if (_monitorCTS == null) _monitorCTS = new CancellationTokenSource();
|
||||
|
||||
// 扫描可用监测项
|
||||
DiscoverAvailableMethods();
|
||||
|
||||
// 启动采样定时器
|
||||
_sampleTimer.Start();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 信号列表项:UI 显示名 + 对应的 OxyPlot LineSeries 引用 + 模拟数据 generator。
|
||||
/// generator(t) 接收当前模拟时间,返回该时刻 y 值。
|
||||
/// </summary>
|
||||
public class SignalItem
|
||||
{
|
||||
public string Name { get; }
|
||||
public LineSeries Series { get; }
|
||||
public Func<double, double> Generator { get; }
|
||||
public SignalItem(string name, LineSeries series, Func<double, double> generator)
|
||||
{
|
||||
Name = name;
|
||||
Series = series;
|
||||
Generator = generator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,17 +16,14 @@
|
||||
<converters:LessThanConverter x:Key="LessThanConverter"/>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- 外层 Border:装 MouseDoubleClickBehavior 实现九宫格双击展开 -->
|
||||
<Border Background="#F5F7FA">
|
||||
<i:Interaction.Behaviors>
|
||||
<b:MouseDoubleClickBehavior
|
||||
Command="{Binding DataContext.RefreshCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
|
||||
</i:Interaction.Behaviors>
|
||||
|
||||
<!-- 给最外层 Grid 命名,方便子控件 DataTrigger 监听 ActualWidth -->
|
||||
<Grid x:Name="RootGrid" Margin="8">
|
||||
<Grid.RowDefinitions>
|
||||
<!-- Row0 标题:窄宽时折叠为 0 高度 -->
|
||||
<RowDefinition>
|
||||
<RowDefinition.Style>
|
||||
<Style TargetType="RowDefinition">
|
||||
@@ -39,7 +36,6 @@
|
||||
</Style>
|
||||
</RowDefinition.Style>
|
||||
</RowDefinition>
|
||||
<!-- Row1 工具栏:窄宽时折叠为 0 -->
|
||||
<RowDefinition>
|
||||
<RowDefinition.Style>
|
||||
<Style TargetType="RowDefinition">
|
||||
@@ -52,9 +48,7 @@
|
||||
</Style>
|
||||
</RowDefinition.Style>
|
||||
</RowDefinition>
|
||||
<!-- Row2 主体(图表区) -->
|
||||
<RowDefinition Height="*"/>
|
||||
<!-- Row3 状态栏:窄宽时折叠为 0 -->
|
||||
<RowDefinition>
|
||||
<RowDefinition.Style>
|
||||
<Style TargetType="RowDefinition">
|
||||
@@ -73,38 +67,19 @@
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="{Binding TestStatus, StringFormat=监控界面 - {0}}"
|
||||
FontSize="20" FontWeight="Bold"
|
||||
Margin="4,0,0,8">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
Margin="4,0,0,8"/>
|
||||
|
||||
<!-- ====== Row1:工具栏 ====== -->
|
||||
<Border Grid.Row="1"
|
||||
Background="White"
|
||||
BorderBrush="#DDD" BorderThickness="1"
|
||||
CornerRadius="4" Padding="8" Margin="0,0,0,6">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button Content="+ 添加信号"
|
||||
Command="{Binding AddSignalCommand}"
|
||||
<Button Content="+ 添加监测项"
|
||||
Command="{Binding AddChannelCommand}"
|
||||
Padding="12,4"/>
|
||||
<Button Content="− 删除信号"
|
||||
Command="{Binding DeleteSignalCommand}"
|
||||
<Button Content="− 删除监测项"
|
||||
Command="{Binding DeleteChannelCommand}"
|
||||
Padding="12,4" Margin="6,0,0,0"/>
|
||||
<Button Content="↺ 复原视图"
|
||||
Command="{Binding ResetViewCommand}"
|
||||
@@ -117,14 +92,13 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- ====== Row2:主体(左信号列表 + 右图表)====== -->
|
||||
<!-- ====== Row2:主体 ====== -->
|
||||
<Grid Grid.Row="2">
|
||||
<Grid.ColumnDefinitions>
|
||||
<!-- Col0 信号列表:窄宽时折叠为 0 宽 -->
|
||||
<ColumnDefinition>
|
||||
<ColumnDefinition.Style>
|
||||
<Style TargetType="ColumnDefinition">
|
||||
<Setter Property="Width" Value="220"/>
|
||||
<Setter Property="Width" Value="280"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Width" Value="0"/>
|
||||
@@ -133,7 +107,7 @@
|
||||
</Style>
|
||||
</ColumnDefinition.Style>
|
||||
</ColumnDefinition>
|
||||
<!-- Col1 拖拽条:窄宽时折叠为 0 宽 -->
|
||||
|
||||
<ColumnDefinition>
|
||||
<ColumnDefinition.Style>
|
||||
<Style TargetType="ColumnDefinition">
|
||||
@@ -149,61 +123,84 @@
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- 左:信号列表(窄宽时整体隐藏) -->
|
||||
<!-- 左侧:可用方法列表 + 已添加监测通道列表 -->
|
||||
<Border Grid.Column="0"
|
||||
Background="White"
|
||||
BorderBrush="#DDD" BorderThickness="1"
|
||||
CornerRadius="4">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<DockPanel>
|
||||
<Border DockPanel.Dock="Top"
|
||||
Background="#ECEFF4"
|
||||
Padding="8,4">
|
||||
<TextBlock Text="信号列表" FontWeight="Bold"/>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 可用方法列表 -->
|
||||
<Border Grid.Row="0" Background="#ECEFF4" Padding="8,4">
|
||||
<TextBlock Text="可用监测项(选择后点击添加)" FontWeight="Bold"/>
|
||||
</Border>
|
||||
<ListBox ItemsSource="{Binding Signals}"
|
||||
SelectedItem="{Binding SelectedSignal}"
|
||||
<ListBox Grid.Row="1"
|
||||
ItemsSource="{Binding AvailableMethods}"
|
||||
SelectedItem="{Binding SelectedAvailableMethod}"
|
||||
BorderThickness="0">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal" Margin="2">
|
||||
<Border Width="12" Height="12"
|
||||
CornerRadius="2"
|
||||
Background="#888"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding Name}"
|
||||
Margin="6,0,0,0"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding DisplayName}" Margin="2"/>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- 分隔 -->
|
||||
<Border Grid.Row="2" Background="#ECEFF4" Padding="8,4">
|
||||
<TextBlock Text="已添加监测通道" FontWeight="Bold"/>
|
||||
</Border>
|
||||
|
||||
<!-- 监测通道列表(带显示/隐藏CheckBox) -->
|
||||
<ListBox Grid.Row="3"
|
||||
ItemsSource="{Binding Channels}"
|
||||
SelectedItem="{Binding SelectedChannel}"
|
||||
BorderThickness="0">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Margin="2">
|
||||
<DockPanel>
|
||||
<!-- 显示/隐藏复选框 -->
|
||||
<CheckBox IsChecked="{Binding IsDisplayed}"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip="勾选=在图表上显示,取消=仅记录不显示"/>
|
||||
<!-- 颜色色块 -->
|
||||
<Border Width="10" Height="10"
|
||||
CornerRadius="2"
|
||||
VerticalAlignment="Center"
|
||||
Margin="4,0,6,0">
|
||||
<Border.Background>
|
||||
<SolidColorBrush Color="SteelBlue"/>
|
||||
</Border.Background>
|
||||
</Border>
|
||||
<TextBlock Text="{Binding DisplayName}"
|
||||
VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</DockPanel>
|
||||
|
||||
<!-- 状态 -->
|
||||
<TextBlock Grid.Row="4"
|
||||
Text="{Binding StatusMessage}"
|
||||
FontSize="11" Foreground="#666"
|
||||
Margin="4,2" TextWrapping="Wrap"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<GridSplitter Grid.Column="1"
|
||||
HorizontalAlignment="Stretch"
|
||||
Background="Transparent">
|
||||
<GridSplitter.Style>
|
||||
<Style TargetType="GridSplitter">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</GridSplitter.Style>
|
||||
</GridSplitter>
|
||||
Background="Transparent"/>
|
||||
|
||||
<!-- 右:OxyPlot 图表(核心,始终显示) -->
|
||||
<!-- 右侧:OxyPlot 图表 -->
|
||||
<Border Grid.Column="2"
|
||||
Background="White"
|
||||
BorderBrush="#DDD" BorderThickness="1"
|
||||
@@ -218,15 +215,6 @@
|
||||
Background="#ECEFF4"
|
||||
Padding="8,4" Margin="0,6,0,0"
|
||||
CornerRadius="2">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ActualWidth, ElementName=RootGrid, Converter={StaticResource LessThanConverter}, ConverterParameter=600}" Value="True">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<TextBlock Text="{Binding StatusMessage}"
|
||||
Foreground="#444"
|
||||
FontSize="12"/>
|
||||
|
||||
71
Service/Implement/MonitorValueService.cs
Normal file
71
Service/Implement/MonitorValueService.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Model;
|
||||
using Model.Entity;
|
||||
using ORM;
|
||||
using Service.Interface;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Service.Implement
|
||||
{
|
||||
/// <summary>
|
||||
/// 监测数值记录服务实现
|
||||
/// </summary>
|
||||
public class MonitorValueService : BaseService<MonitorValueEntity>, IMonitorValueService
|
||||
{
|
||||
// 继承父类构造函数,注入 SqlSugar 仓储
|
||||
public MonitorValueService(SqlSugarRepository<MonitorValueEntity> repository) : base(repository)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量插入监测数据
|
||||
/// </summary>
|
||||
public async Task<Result<bool>> InsertRangeAsync(List<MonitorValueEntity> entities)
|
||||
{
|
||||
if (entities == null || entities.Count == 0)
|
||||
return Result<bool>.Success(true);
|
||||
|
||||
try
|
||||
{
|
||||
// 使用 SqlSugar 的批量插入,底层会转换为 BulkCopy 或是批量 SQL,速度极快
|
||||
var result = await _repository.Context.Insertable(entities).ExecuteCommandAsync();
|
||||
return Result<bool>.Success(result > 0);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result<bool>.Error("批量插入监测数据失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据监测通道名称,分页查询历史记录
|
||||
/// </summary>
|
||||
public async Task<Result<List<MonitorValueEntity>>> GetPagedByNameAsync(string monitorName, int pageIndex, int pageSize, RefAsync<int> total)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _repository.Entities;
|
||||
|
||||
// 如果传了名字则按名字过滤
|
||||
if (!string.IsNullOrEmpty(monitorName))
|
||||
{
|
||||
query = query.Where(x => x.MonitorName == monitorName);
|
||||
}
|
||||
|
||||
var list = await query
|
||||
.OrderByDescending(d => d.CreateTime) // 监测项通常优先看最新的数据
|
||||
.ToPageListAsync(pageIndex, pageSize, total);
|
||||
|
||||
// 计算总页数
|
||||
total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
|
||||
return Result<List<MonitorValueEntity>>.Success(list);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result<List<MonitorValueEntity>>.Error($"根据名称 [{monitorName}] 分页查询数据失败", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
32
Service/Interface/IMonitorValueService.cs
Normal file
32
Service/Interface/IMonitorValueService.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Model;
|
||||
using Model.Entity;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Service.Interface
|
||||
{
|
||||
/// <summary>
|
||||
/// 监测数值记录服务接口
|
||||
/// </summary>
|
||||
public interface IMonitorValueService : IBaseService<MonitorValueEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// 批量插入监测数据(工控高频采样推荐使用,性能远高于单条循环插入)
|
||||
/// </summary>
|
||||
/// <param name="entities">实体集合</param>
|
||||
/// <returns>返回操作是否成功的 Result</returns>
|
||||
Task<Result<bool>> InsertRangeAsync(List<MonitorValueEntity> entities);
|
||||
|
||||
/// <summary>
|
||||
/// 根据监测通道名称,分页查询历史记录
|
||||
/// </summary>
|
||||
/// <param name="monitorName">通道名称(例如:台架1.读取主轴温度)</param>
|
||||
/// <param name="pageIndex">页码</param>
|
||||
/// <param name="pageSize">每页大小</param>
|
||||
/// <param name="total">总条数输出</param>
|
||||
/// <returns>分页数据结果</returns>
|
||||
Task<Result<List<MonitorValueEntity>>> GetPagedByNameAsync(string monitorName, int pageIndex, int pageSize, RefAsync<int> total);
|
||||
}
|
||||
}
|
||||
@@ -448,7 +448,7 @@
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Grid.Column="0"
|
||||
Minimum="0" Maximum="100"
|
||||
Minimum="100" Maximum="200"
|
||||
TickFrequency="10" IsSnapToTickEnabled="True"
|
||||
VerticalAlignment="Center"
|
||||
Value="{Binding SystemConfig.PerformanceLevel}"/>
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
<DataGrid dd:DragDrop.IsDragSource="{Binding Admin}"
|
||||
dd:DragDrop.IsDropTarget="{Binding Admin}"
|
||||
dd:DragDrop.UseDefaultDragAdorner="{Binding Admin}"
|
||||
VirtualizingStackPanel.IsVirtualizing="True"
|
||||
VirtualizingStackPanel.VirtualizationMode="Recycling"
|
||||
VirtualizingStackPanel.ScrollUnit="Pixel"
|
||||
AutoGenerateColumns="False"
|
||||
Background="Transparent"
|
||||
CanUserAddRows="False"
|
||||
|
||||
@@ -18,7 +18,7 @@ using static UIShare.UIViewModel.ParameterVM;
|
||||
|
||||
namespace UIShare
|
||||
{
|
||||
public class StepRunning
|
||||
public class StepRunning:IDisposable
|
||||
{
|
||||
private ScopedContext _scopedContext;
|
||||
private SystemConfig _systemConfig;
|
||||
@@ -39,6 +39,9 @@ namespace UIShare
|
||||
public CancellationTokenSource errorStepCTS = new();
|
||||
private bool SubSingleStep = false;
|
||||
|
||||
/// <summary>标记是否已被注销,执行方法据此安全退出</summary>
|
||||
private volatile bool _disposed = false;
|
||||
|
||||
private Guid TestRoundID;
|
||||
public StepRunning(ScopedContext ScopedContext, SystemConfig systemConfig,IEventAggregator eventAggregator, DeviceManager deviceManager)
|
||||
{
|
||||
@@ -50,6 +53,7 @@ namespace UIShare
|
||||
}
|
||||
public async Task<bool> ExecuteErrorSteps(ProgramVM program, int depth = 0, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
int index = 0;
|
||||
bool stepSuccess = false;
|
||||
if (depth == 0)
|
||||
@@ -67,7 +71,7 @@ namespace UIShare
|
||||
|
||||
while (index < program.ErrorStepCollection.Count)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
if (_disposed || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -215,6 +219,7 @@ namespace UIShare
|
||||
}
|
||||
public async Task<bool> ExecuteSteps(ProgramVM program, int depth = 0, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) return false;
|
||||
int index = 0;
|
||||
bool stepSuccess = false;
|
||||
if (depth == 0)
|
||||
@@ -232,11 +237,11 @@ namespace UIShare
|
||||
|
||||
while (index < program.StepCollection.Count)
|
||||
{
|
||||
while (_scopedContext.IsStop == true)
|
||||
while (!_disposed && _scopedContext.IsStop == true)
|
||||
{
|
||||
await Task.Delay(50);
|
||||
await Task.Delay(50, cancellationToken);
|
||||
}
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
if (_disposed || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -392,11 +397,12 @@ namespace UIShare
|
||||
|
||||
public async Task ExecuteMethodStep(StepVM step, Dictionary<Guid, ParameterVM> parameters, int depth, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
if(_scopedContext.Program.StepCollection.Count>1)
|
||||
_scopedContext.SelectedStep = null;
|
||||
await Task.Delay(_systemConfig.PerformanceLevel);
|
||||
await Task.Delay(_systemConfig.PerformanceLevel, cancellationToken);
|
||||
|
||||
|
||||
// 1. 查找类型
|
||||
@@ -711,6 +717,40 @@ namespace UIShare
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
// 1. 唤醒暂停循环(IsStop 可能卡住后台线程)
|
||||
try
|
||||
{
|
||||
if (_scopedContext != null)
|
||||
{
|
||||
_scopedContext.IsStop = false;
|
||||
_scopedContext.IsTerminate = true;
|
||||
_scopedContext.RunState = "运行";
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
try
|
||||
{
|
||||
if (stepCTS != null && !stepCTS.IsCancellationRequested) stepCTS.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException) { }
|
||||
|
||||
try
|
||||
{
|
||||
if (errorStepCTS != null && !errorStepCTS.IsCancellationRequested) errorStepCTS.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException) { }
|
||||
|
||||
tmpParameters.Clear();
|
||||
loopStack.Clear();
|
||||
loopStopwatchStack.Clear();
|
||||
stepStopwatch.Stop();
|
||||
}
|
||||
|
||||
|
||||
|
||||
#region 私有类
|
||||
|
||||
Reference in New Issue
Block a user