RealTimeLineChart.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using Microsoft.Win32;
  2. using ScottPlot;
  3. using ScottPlot.Plottables;
  4. using ScottPlot.WPF;
  5. using SWRIS.Core;
  6. using SWRIS.Models;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Threading;
  14. namespace SWRIS.Controls
  15. {
  16. /// <summary>
  17. /// 动态折线图用户控件(基于 ScottPlot.WPF 的高性能版本)
  18. /// </summary>
  19. public partial class RealTimeLineChart : UserControl
  20. {
  21. #region 依赖属性定义
  22. public static readonly DependencyProperty SensorCountProperty =
  23. DependencyProperty.Register(
  24. nameof(SensorCount),
  25. typeof(int),
  26. typeof(RealTimeLineChart),
  27. new PropertyMetadata(4, OnSensorCountChanged));
  28. public static readonly DependencyProperty RopeLengthProperty =
  29. DependencyProperty.Register(
  30. nameof(RopeLength),
  31. typeof(double),
  32. typeof(RealTimeLineChart),
  33. new PropertyMetadata(100.0, OnAxisXChanged));
  34. public static readonly DependencyProperty SamplingStepProperty =
  35. DependencyProperty.Register(
  36. nameof(SamplingStep),
  37. typeof(double),
  38. typeof(RealTimeLineChart),
  39. new PropertyMetadata(0.1275));
  40. #endregion
  41. #region CLR 包装属性
  42. public int SensorCount
  43. {
  44. get => (int)GetValue(SensorCountProperty);
  45. set => SetValue(SensorCountProperty, value);
  46. }
  47. public double RopeLength
  48. {
  49. get => (double)GetValue(RopeLengthProperty);
  50. set => SetValue(RopeLengthProperty, value);
  51. }
  52. public double SamplingStep
  53. {
  54. get => (double)GetValue(SamplingStepProperty);
  55. set => SetValue(SamplingStepProperty, value);
  56. }
  57. #endregion
  58. public double? _lastPosition = null;
  59. private ConcurrentQueue<ushort> _sensorDataQueues;
  60. private const double MINDAMAGE = 40; // 最小损伤值
  61. private const double MAXDAMAGE = 120; // 最大损伤值
  62. private int _displayPoints = 1000000; // 显示点数
  63. private DispatcherTimer UpdatePlotTimer;
  64. private DataLogger _dataLogger;
  65. public RealTimeLineChart()
  66. {
  67. InitializeComponent();
  68. InitializePlot();
  69. }
  70. private void OnLoaded(object sender, RoutedEventArgs e)
  71. {
  72. InitializePlot();
  73. }
  74. #region 初始化方法
  75. private void InitializePlot()
  76. {
  77. WpfPlot.Menu?.Clear();
  78. WpfPlot.Menu.Add("保存图片", pt =>
  79. {
  80. OpenSaveImageDialog(pt);
  81. });
  82. WpfPlot.Menu.Add("清除曲线", pt =>
  83. {
  84. ClearPoints();
  85. });
  86. WpfPlot.Menu.Add("重置视图", pt =>
  87. {
  88. SetLimits();
  89. });
  90. var plot = WpfPlot.Plot;
  91. plot.Clear();
  92. plot.DataBackground.Color = Colors.Transparent;
  93. plot.FigureBackground.Color = Colors.Transparent;
  94. plot.Grid.MajorLineColor = new Color(59, 59, 123).WithOpacity(0.6);
  95. plot.Grid.XAxis.TickLabelStyle.ForeColor = new Color(151, 166, 212);
  96. plot.Grid.YAxis.TickLabelStyle.ForeColor = new Color(151, 166, 212);
  97. plot.Grid.XAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  98. plot.Grid.XAxis.FrameLineStyle.Width = 2;
  99. plot.Grid.YAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  100. plot.Grid.YAxis.FrameLineStyle.Width = 2;
  101. plot.Grid.XAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  102. plot.Grid.XAxis.MajorTickStyle.Width = 1;
  103. plot.Grid.YAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  104. plot.Grid.YAxis.MajorTickStyle.Width = 1;
  105. plot.Grid.YAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  106. plot.Grid.XAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  107. plot.Axes.Hairline(false);
  108. _sensorDataQueues = new ConcurrentQueue<ushort>();
  109. _dataLogger = plot.Add.DataLogger();
  110. _dataLogger.LineWidth = 2;
  111. _dataLogger.Color = new Color("#f47c7c");
  112. _dataLogger.ManageAxisLimits = false;
  113. WpfPlot.Plot.Axes.SetLimits(0, RopeLength * 1.2, MINDAMAGE, MAXDAMAGE);
  114. WpfPlot.Refresh();
  115. UpdatePlotTimer?.Stop();
  116. UpdatePlotTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
  117. UpdatePlotTimer.Tick += (s, d) =>
  118. {
  119. if (_dataLogger.HasNewData)
  120. {
  121. SetLimits();
  122. }
  123. };
  124. UpdatePlotTimer.Start();
  125. }
  126. #endregion
  127. #region 数据操作方法
  128. private void SetLimits()
  129. {
  130. if (_lastPosition == null || _lastPosition.Value < RopeLength)
  131. {
  132. WpfPlot.Plot.Axes.SetLimits(0, RopeLength * 1.2, MINDAMAGE, MAXDAMAGE);
  133. }
  134. else
  135. {
  136. WpfPlot.Plot.Axes.SetLimits(0, _lastPosition.Value + (RopeLength * 0.12), MINDAMAGE, MAXDAMAGE);
  137. }
  138. WpfPlot.Refresh();
  139. }
  140. public void ClearPoints()
  141. {
  142. lock (_sensorDataQueues)
  143. {
  144. while (_sensorDataQueues.TryDequeue(out _)) ;
  145. }
  146. _dataLogger.Clear();
  147. WpfPlot.Refresh();
  148. }
  149. public void AddDataPoints(Coordinates[] chartData)
  150. {
  151. _dataLogger.Add(chartData);
  152. _lastPosition = chartData.LastOrDefault().X;
  153. WpfPlot.Refresh();
  154. }
  155. public Coordinates[] GetChartSource()
  156. {
  157. return _dataLogger.Data.Coordinates.ToArray();
  158. }
  159. public void AddDataPoints((double Position, LiveStreamDataModel ListStream) dataPoints, int[] inUseSensors)
  160. {
  161. if (_lastPosition == null)
  162. {
  163. _lastPosition = dataPoints.Position;
  164. return;
  165. }
  166. if (dataPoints.Position < _lastPosition)
  167. {
  168. lock (_sensorDataQueues)
  169. {
  170. while (_sensorDataQueues.TryDequeue(out _)) ;
  171. _lastPosition = dataPoints.Position;
  172. }
  173. _dataLogger.Data.Clear();
  174. }
  175. if (inUseSensors == null || inUseSensors.Length == 0)
  176. {
  177. return;
  178. }
  179. for (int i = 0; i < dataPoints.ListStream.SampleCount; i++)
  180. {
  181. ushort totalValue = 0;
  182. ushort totalCount = 0;
  183. ushort[] values = dataPoints.ListStream.Data[i];
  184. foreach (var j in inUseSensors)
  185. {
  186. totalCount++;
  187. totalValue += values[j - 1];
  188. }
  189. var value = (ushort)(totalValue / totalCount);
  190. _sensorDataQueues.Enqueue(value);
  191. }
  192. if (dataPoints.Position > _lastPosition)
  193. {
  194. UpdateLoop(_lastPosition.Value, dataPoints.Position);
  195. _lastPosition = dataPoints.Position;
  196. }
  197. }
  198. public void OpenSaveImageDialog(Plot plot)
  199. {
  200. SaveFileDialog saveFileDialog = new SaveFileDialog
  201. {
  202. Filter = "PNG Files (*.png)|*.png|JPEG Files (*.jpg, *.jpeg)|*.jpg;*.jpeg|BMP Files (*.bmp)|*.bmp|WebP Files (*.webp)|*.webp|SVG Files (*.svg)|*.svg|All files (*.*)|*.*"
  203. };
  204. bool? flag = saveFileDialog.ShowDialog();
  205. if (flag.HasValue && flag == true && !string.IsNullOrEmpty(saveFileDialog.FileName))
  206. {
  207. ImageFormat format;
  208. try
  209. {
  210. format = ImageFormats.FromFilename(saveFileDialog.FileName);
  211. }
  212. catch (ArgumentException)
  213. {
  214. MessageBox.Show("Unsupported image file format", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  215. return;
  216. }
  217. try
  218. {
  219. PixelSize size = plot.RenderManager.LastRender.FigureRect.Size;
  220. plot.Save(saveFileDialog.FileName, (int)size.Width, (int)size.Height, format);
  221. }
  222. catch (Exception)
  223. {
  224. MessageBox.Show("Image save failed", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  225. }
  226. }
  227. }
  228. private void UpdateLoop(double lastPosition, double position)
  229. {
  230. try
  231. {
  232. // 在后台线程准备数据
  233. List<(double x, ushort y)> dataToAdd = new List<(double x, ushort y)>();
  234. var step = (position - lastPosition) / Math.Max(1, _sensorDataQueues.Count);
  235. double currentX = lastPosition;
  236. while (_sensorDataQueues.TryDequeue(out ushort data))
  237. {
  238. currentX += step;
  239. // 确保 x 值严格递增
  240. if (dataToAdd.Count > 0 && currentX <= dataToAdd[dataToAdd.Count - 1].x)
  241. {
  242. currentX = dataToAdd[dataToAdd.Count - 1].x + Math.Abs(step) * 0.001;
  243. }
  244. dataToAdd.Add((currentX, data));
  245. }
  246. // 在UI线程批量添加
  247. Dispatcher.Invoke(() =>
  248. {
  249. lock (_dataLogger)
  250. {
  251. // 获取最后一个点的 x 值
  252. double lastX = _dataLogger.Data.Coordinates.Count > 0
  253. ? _dataLogger.Data.Coordinates[_dataLogger.Data.Coordinates.Count - 1].X
  254. : double.MinValue;
  255. foreach (var point in dataToAdd)
  256. {
  257. double safeX = point.x;
  258. if (safeX <= lastX)
  259. {
  260. safeX = lastX + Math.Abs(position - lastPosition) * 0.0001;
  261. }
  262. _dataLogger.Add(safeX, point.y);
  263. lastX = safeX;
  264. }
  265. }
  266. // 清理操作
  267. if (_dataLogger.Data.Coordinates.Count > _displayPoints)
  268. {
  269. int removeCount = (int)(_displayPoints * 0.1d);
  270. removeCount = Math.Min(removeCount, _dataLogger.Data.Coordinates.Count - 1);
  271. if (removeCount > 0)
  272. {
  273. _dataLogger.Data.Coordinates.RemoveRange(0, removeCount);
  274. }
  275. }
  276. });
  277. }
  278. catch (Exception ex)
  279. {
  280. LogHelper.Error($"绘制曲线时发生错误:{ex.Message}", ex);
  281. }
  282. }
  283. #endregion
  284. #region 静态回调
  285. private static void OnSensorCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  286. {
  287. if (d is RealTimeLineChart control)
  288. control.OnSensorCountChanged((int)e.OldValue, (int)e.NewValue);
  289. }
  290. private static void OnAxisXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  291. {
  292. if (d is RealTimeLineChart control)
  293. control.UpdateAxisX();
  294. }
  295. #endregion
  296. #region 坐标轴更新逻辑
  297. private void UpdateAxisX()
  298. {
  299. if (WpfPlot?.Plot == null) return;
  300. WpfPlot.Plot.Axes.SetLimitsX(0, RopeLength * 1.2);
  301. WpfPlot.Refresh();
  302. }
  303. #endregion
  304. #region 传感器数量变化处理
  305. private void OnSensorCountChanged(int oldCount, int newCount)
  306. {
  307. Dispatcher.Invoke(() =>
  308. {
  309. InitializePlot();
  310. });
  311. }
  312. #endregion
  313. }
  314. }