RealTimeLineChart.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. /// 动态折线图用户控件
  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.YAxis.TickLabelStyle.FontSize = 9;
  98. plot.Grid.XAxis.TickLabelStyle.FontSize = 9;
  99. plot.Grid.XAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  100. plot.Grid.XAxis.FrameLineStyle.Width = 2;
  101. plot.Grid.YAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  102. plot.Grid.YAxis.FrameLineStyle.Width = 2;
  103. plot.Grid.XAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  104. plot.Grid.XAxis.MajorTickStyle.Width = 1;
  105. plot.Grid.YAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  106. plot.Grid.YAxis.MajorTickStyle.Width = 1;
  107. plot.Grid.YAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  108. plot.Grid.XAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  109. plot.Axes.Hairline(false);
  110. _sensorDataQueues = new ConcurrentQueue<ushort>();
  111. _dataLogger = plot.Add.DataLogger();
  112. _dataLogger.LineWidth = 2;
  113. _dataLogger.Color = new Color("#f47c7c");
  114. _dataLogger.ManageAxisLimits = false;
  115. WpfPlot.Plot.Axes.SetLimits(0, RopeLength * 1.2, MINDAMAGE, MAXDAMAGE);
  116. WpfPlot.Refresh();
  117. UpdatePlotTimer?.Stop();
  118. UpdatePlotTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
  119. UpdatePlotTimer.Tick += (s, d) =>
  120. {
  121. if (_dataLogger.HasNewData)
  122. {
  123. SetLimits();
  124. }
  125. };
  126. UpdatePlotTimer.Start();
  127. }
  128. #endregion
  129. #region 数据操作方法
  130. private void SetLimits()
  131. {
  132. if (_lastPosition == null || _lastPosition.Value < RopeLength)
  133. {
  134. WpfPlot.Plot.Axes.SetLimits(0, RopeLength * 1.2, MINDAMAGE, MAXDAMAGE);
  135. }
  136. else
  137. {
  138. WpfPlot.Plot.Axes.SetLimits(0, _lastPosition.Value + (RopeLength * 0.12), MINDAMAGE, MAXDAMAGE);
  139. }
  140. WpfPlot.Refresh();
  141. }
  142. public void ClearPoints()
  143. {
  144. lock (_sensorDataQueues)
  145. {
  146. while (_sensorDataQueues.TryDequeue(out _)) ;
  147. }
  148. _dataLogger.Clear();
  149. WpfPlot.Refresh();
  150. }
  151. public void AddDataPoints(Coordinates[] chartData)
  152. {
  153. if (chartData == null || chartData.Length == 0 || _dataLogger.Data.Coordinates.Any())
  154. return;
  155. // 检查是否需要排序
  156. var sortedData = chartData;
  157. bool isAscending = true;
  158. for (int i = 1; i < chartData.Length; i++)
  159. {
  160. if (chartData[i].X < chartData[i - 1].X)
  161. {
  162. isAscending = false;
  163. break;
  164. }
  165. }
  166. // 如果不是升序,进行排序
  167. if (!isAscending)
  168. {
  169. sortedData = chartData.OrderBy(p => p.X).ToArray();
  170. }
  171. _dataLogger.Add(sortedData);
  172. _lastPosition = sortedData.LastOrDefault().X;
  173. WpfPlot.Refresh();
  174. }
  175. public Coordinates[] GetChartSource()
  176. {
  177. return _dataLogger.Data.Coordinates.ToArray();
  178. }
  179. public void AddDataPoints((double Position, LiveStreamDataModel ListStream) dataPoints, int[] inUseSensors)
  180. {
  181. if (_lastPosition == null)
  182. {
  183. _lastPosition = dataPoints.Position;
  184. return;
  185. }
  186. if (dataPoints.Position < _lastPosition)
  187. {
  188. lock (_sensorDataQueues)
  189. {
  190. while (_sensorDataQueues.TryDequeue(out _)) ;
  191. _lastPosition = dataPoints.Position;
  192. }
  193. _dataLogger.Data.Clear();
  194. }
  195. if (inUseSensors == null || inUseSensors.Length == 0 || inUseSensors.Any(c => c >= dataPoints.ListStream.SensorCount))
  196. {
  197. inUseSensors = Enumerable.Range(1, dataPoints.ListStream.SensorCount).ToArray();
  198. }
  199. for (int i = 0; i < dataPoints.ListStream.SampleCount; i++)
  200. {
  201. ushort totalValue = 0;
  202. ushort totalCount = 0;
  203. ushort[] values = dataPoints.ListStream.Data[i];
  204. foreach (var j in inUseSensors)
  205. {
  206. totalCount++;
  207. totalValue += values[j - 1];
  208. }
  209. var value = (ushort)(totalValue / totalCount);
  210. _sensorDataQueues.Enqueue(value);
  211. }
  212. if (dataPoints.Position > _lastPosition)
  213. {
  214. UpdateLoop(_lastPosition.Value, dataPoints.Position);
  215. _lastPosition = dataPoints.Position;
  216. }
  217. }
  218. public void OpenSaveImageDialog(Plot plot)
  219. {
  220. SaveFileDialog saveFileDialog = new SaveFileDialog
  221. {
  222. 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 (*.*)|*.*"
  223. };
  224. bool? flag = saveFileDialog.ShowDialog();
  225. if (flag.HasValue && flag == true && !string.IsNullOrEmpty(saveFileDialog.FileName))
  226. {
  227. ImageFormat format;
  228. try
  229. {
  230. format = ImageFormats.FromFilename(saveFileDialog.FileName);
  231. }
  232. catch (ArgumentException)
  233. {
  234. MessageBox.Show("Unsupported image file format", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  235. return;
  236. }
  237. try
  238. {
  239. PixelSize size = plot.RenderManager.LastRender.FigureRect.Size;
  240. plot.Save(saveFileDialog.FileName, (int)size.Width, (int)size.Height, format);
  241. }
  242. catch (Exception)
  243. {
  244. MessageBox.Show("Image save failed", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  245. }
  246. }
  247. }
  248. /// <summary>
  249. /// 更新曲线绘制的循环方法,将队列中的数据批量添加到曲线中,并确保 x 值严格递增
  250. /// </summary>
  251. /// <param name="lastPosition">上一个位置</param>
  252. /// <param name="position">当前位置</param>
  253. private void UpdateLoop(double lastPosition, double position)
  254. {
  255. try
  256. {
  257. // 在后台线程准备数据
  258. List<(double x, ushort y)> dataToAdd = new List<(double x, ushort y)>();
  259. var step = (position - lastPosition) / Math.Max(1, _sensorDataQueues.Count);
  260. double currentX = lastPosition;
  261. while (_sensorDataQueues.TryDequeue(out ushort data))
  262. {
  263. currentX += step;
  264. // 确保 x 值严格递增
  265. if (dataToAdd.Count > 0 && currentX <= dataToAdd[dataToAdd.Count - 1].x)
  266. {
  267. currentX = dataToAdd[dataToAdd.Count - 1].x + Math.Abs(step) * 0.001;
  268. }
  269. dataToAdd.Add((currentX, data));
  270. }
  271. // 在UI线程批量添加
  272. Dispatcher.Invoke(() =>
  273. {
  274. lock (_dataLogger)
  275. {
  276. // 获取最后一个点的 x 值
  277. double lastX = _dataLogger.Data.Coordinates.Count > 0
  278. ? _dataLogger.Data.Coordinates[_dataLogger.Data.Coordinates.Count - 1].X
  279. : double.MinValue;
  280. foreach (var point in dataToAdd)
  281. {
  282. double safeX = point.x;
  283. if (safeX <= lastX)
  284. {
  285. safeX = lastX + Math.Abs(position - lastPosition) * 0.0001;
  286. }
  287. _dataLogger.Add(safeX, point.y);
  288. lastX = safeX;
  289. }
  290. }
  291. // 清理操作
  292. if (_dataLogger.Data.Coordinates.Count > _displayPoints)
  293. {
  294. int removeCount = (int)(_displayPoints * 0.1d);
  295. removeCount = Math.Min(removeCount, _dataLogger.Data.Coordinates.Count - 1);
  296. if (removeCount > 0)
  297. {
  298. _dataLogger.Data.Coordinates.RemoveRange(0, removeCount);
  299. }
  300. }
  301. });
  302. }
  303. catch (Exception ex)
  304. {
  305. LogHelper.Error($"绘制曲线时发生错误:{ex.Message}", ex);
  306. }
  307. }
  308. #endregion
  309. #region 静态回调
  310. private static void OnSensorCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  311. {
  312. if (d is RealTimeLineChart control)
  313. control.OnSensorCountChanged((int)e.OldValue, (int)e.NewValue);
  314. }
  315. private static void OnAxisXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  316. {
  317. if (d is RealTimeLineChart control)
  318. control.UpdateAxisX();
  319. }
  320. #endregion
  321. #region 坐标轴更新逻辑
  322. private void UpdateAxisX()
  323. {
  324. if (WpfPlot?.Plot == null) return;
  325. WpfPlot.Plot.Axes.SetLimitsX(0, RopeLength * 1.2);
  326. WpfPlot.Refresh();
  327. }
  328. #endregion
  329. #region 传感器数量变化处理
  330. private void OnSensorCountChanged(int oldCount, int newCount)
  331. {
  332. Dispatcher.Invoke(() =>
  333. {
  334. InitializePlot();
  335. });
  336. }
  337. #endregion
  338. }
  339. }