DataViewModel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Forms;
  15. using Aitex.Core.RT.Log;
  16. using Aitex.Sorter.Common;
  17. using MECF.Framework.Common.DataCenter;
  18. using MECF.Framework.Common.Equipment;
  19. using MECF.Framework.UI.Client.CenterViews.DataLogs.Event;
  20. using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
  21. #if !EXPORT_TO_CSV
  22. using MECF.Framework.Common.Utilities;
  23. #endif
  24. using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
  25. using MECF.Framework.UI.Client.ClientBase;
  26. using MECF.Framework.UI.Client.ClientBase.Charting;
  27. using MECF.Framework.UI.Client.ClientBase.EventArgs;
  28. using MECF.Framework.UI.Client.ClientBase.Pipelines;
  29. using MECF.Framework.UI.Client.ClientBase.Tree;
  30. using SciChart.Charting.Model.DataSeries;
  31. using SciChart.Charting.Visuals.Axes;
  32. using SciChart.Charting.Visuals.RenderableSeries;
  33. using SciChart.Core.Extensions;
  34. using SciChart.Core.Framework;
  35. using SciChart.Data.Model;
  36. using Cali = Caliburn.Micro;
  37. using DataGridCell = System.Windows.Controls.DataGridCell;
  38. using DateRange = SciChart.Data.Model.DateRange;
  39. using MessageBox = System.Windows.MessageBox;
  40. using TreeNode = MECF.Framework.UI.Client.ClientBase.Tree.TreeNode;
  41. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
  42. {
  43. public class DataViewModel : BusyIndicateableUiViewModelBase
  44. {
  45. #region Variables
  46. /// <summary>
  47. /// 一次最多查询的项目数。
  48. /// </summary>
  49. private const int MAX_ITEMS_PER_QUERY = 50;
  50. private IRange _timeRange;
  51. private IRange _visibleRangeValue;
  52. private AutoRange _autoRange;
  53. private CancellationTokenSource _cancellationTokenSource;
  54. /// <summary>
  55. /// 更新报告导出信息。
  56. /// </summary>
  57. private readonly IProgress<ProgressUpdatingEventArgs> _progCsvExport;
  58. /// <summary>
  59. /// 查询进度信息更新。
  60. /// </summary>
  61. private IProgress<ProgressUpdatingEventArgs> _progQueryUpdate;
  62. /// <summary>
  63. /// 挂起或恢复Chart更新
  64. /// </summary>
  65. private readonly IProgress<bool> _progChartSuspendUpdating;
  66. private IUpdateSuspender _suspender;
  67. /// <summary>
  68. /// 打开错误消息对话框。
  69. /// </summary>
  70. private readonly IProgress<string> _progShowErrorMessageBox;
  71. #endregion
  72. #region Constructors
  73. public DataViewModel()
  74. {
  75. DisplayName = "Data History";
  76. SelectedData = new ChartingLineSeriesCollection(DisplayName);
  77. var now = DateTime.Today;
  78. SearchBeginTime = DateTime.Now.AddHours(-1); // -new TimeSpan(1, 0, 0, 0);
  79. SearchEndTime = DateTime.Now;
  80. //SearchBeginTime = new DateTime(now.Year, now.Month, now.Day, 00, 00, 00); ;// -new TimeSpan(1, 0, 0, 0);
  81. //SearchEndTime = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
  82. var provider = new RealtimeProvider();
  83. ParameterNodes = new TreeNode(DisplayName)
  84. {
  85. MaxTerminalSelectionAllowed = MAX_ITEMS_PER_QUERY
  86. };
  87. ParameterNodes.ChildNodes.AddRange(provider.GetTreeNodeParameters());
  88. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(-60), DateTime.Now.AddMinutes(60));
  89. VisibleRangeValue = new DoubleRange(0, 10);
  90. _progQueryUpdate = new Progress<ProgressUpdatingEventArgs>(e =>
  91. {
  92. if (e.CurrentProgress == e.TotalProgress)
  93. {
  94. IsBusy = false;
  95. if (_cancellationTokenSource?.Token.IsCancellationRequested == false)
  96. {
  97. foreach (var renderableSeries in SelectedData)
  98. {
  99. var series = renderableSeries as FastLineSeries;
  100. var dataSeries = series?.GetDataSeries();
  101. try
  102. {
  103. if (series != null && dataSeries != null)
  104. {
  105. var node = series.BackendParameterNode;
  106. if (double.IsInfinity((double)dataSeries.YRange.Diff))
  107. {
  108. node.ClearStatistic();
  109. }
  110. else
  111. {
  112. var min = ((double)dataSeries.YMin);
  113. var max = ((double)dataSeries.YMax);
  114. var average =
  115. dataSeries.Metadata.Cast<ParameterNodePoint>().Average(x => x.Value);
  116. node.SetStatistic(min, max, average);
  117. }
  118. }
  119. }
  120. catch (Exception ex)
  121. {
  122. var err = $"It's failed to load data of {series?.DataName ?? "Unknown"}, {ex.Message}";
  123. LOG.Error(err, ex);
  124. }
  125. }
  126. }
  127. ChartAutoRange = AutoRange.Never;
  128. ((DataView)View).chart.ZoomExtents();
  129. }
  130. BusyIndicatorContent = e.Message;
  131. });
  132. _progCsvExport = new Progress<ProgressUpdatingEventArgs>(e =>
  133. {
  134. BusyIndicatorContent = e.Message;
  135. });
  136. _progChartSuspendUpdating = new Progress<bool>(isSuspend =>
  137. {
  138. if (isSuspend)
  139. _suspender = ((DataView)View).chart.SuspendSuspendUpdates();
  140. else
  141. {
  142. try
  143. {
  144. if (_suspender?.IsSuspended == true)
  145. _suspender?.SafeDispose();
  146. }
  147. catch (Exception)
  148. {
  149. // 查询过程最后会强制恢复挂起一次,可能引发异常,忽略此异常。
  150. }
  151. }
  152. });
  153. _progShowErrorMessageBox = new Progress<string>((error =>
  154. {
  155. System.Windows.Forms.MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  156. }));
  157. }
  158. #endregion
  159. #region Property
  160. public bool IsPermission => Permission == 3;
  161. private DataView view;
  162. public TreeNode ParameterNodes { get; }
  163. public ChartingLineSeriesCollection SelectedData { get; set; }
  164. public AutoRange ChartAutoRange
  165. {
  166. get => _autoRange;
  167. set
  168. {
  169. _autoRange = value;
  170. NotifyOfPropertyChange(nameof(ChartAutoRange));
  171. }
  172. }
  173. public IRange VisibleRangeTime
  174. {
  175. get => _timeRange;
  176. set
  177. {
  178. _timeRange = value;
  179. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  180. }
  181. }
  182. public IRange VisibleRangeValue
  183. {
  184. get => _visibleRangeValue;
  185. set
  186. {
  187. _visibleRangeValue = value;
  188. NotifyOfPropertyChange(nameof(VisibleRangeValue));
  189. }
  190. }
  191. //public DateTime StartDateTime
  192. //{
  193. // get => ((DataView)View).wfTimeFrom.Value;
  194. // set
  195. // {
  196. // ((DataView)View).wfTimeFrom.Value = value;
  197. // NotifyOfPropertyChange(nameof(StartDateTime));
  198. // }
  199. //}
  200. //public DateTime EndDateTime
  201. //{
  202. // get => ((DataView)View).wfTimeTo.Value;
  203. // set
  204. // {
  205. // ((DataView)View).wfTimeTo.Value = value;
  206. // NotifyOfPropertyChange(nameof(EndDateTime));
  207. // }
  208. //}
  209. public DateTime SearchBeginTime { get; set; }
  210. public DateTime SearchEndTime { get; set; }
  211. #endregion
  212. #region Methods
  213. protected override void OnViewLoaded(object view)
  214. {
  215. base.OnViewLoaded(view);
  216. this.view = (DataView)view;
  217. //StartDateTime = DateTime.Now.Date;
  218. //EndDateTime = DateTime.Now.Date.AddDays(1).AddTicks(-1);
  219. this.view.wfTimeFrom.Content = SearchBeginTime.ToString("yyyy-MM-dd HH:mm:ss");
  220. this.view.wfTimeTo.Content = SearchEndTime.ToString("yyyy-MM-dd HH:mm:ss");
  221. }
  222. public void SelectDate(string SelectType)
  223. {
  224. var windowManager = Caliburn.Micro.Core.IoC.Get<Caliburn.Micro.IWindowManager>();
  225. if (SelectType == "Start")
  226. {
  227. this.SearchBeginTime = Convert.ToDateTime(this.view.wfTimeFrom.Content);
  228. SelectDateViewModel selectdateViewModel = new SelectDateViewModel(SearchBeginTime);
  229. var result = (windowManager as Caliburn.Micro.WindowManager)?.ShowDialogWithTitle(selectdateViewModel, null, "Start Time");
  230. if (result == true)
  231. {
  232. SearchBeginTime = selectdateViewModel.SearchDate;
  233. this.view.wfTimeFrom.Content = selectdateViewModel.SearchDate;
  234. }
  235. }
  236. else
  237. {
  238. this.SearchEndTime = Convert.ToDateTime(this.view.wfTimeTo.Content);
  239. SelectDateViewModel selectdateViewModel = new SelectDateViewModel(SearchEndTime);
  240. var result = (windowManager as Caliburn.Micro.WindowManager)?.ShowDialogWithTitle(selectdateViewModel, null, "End Time");
  241. if (result == true)
  242. {
  243. this.view.wfTimeTo.Content = selectdateViewModel.SearchDate;
  244. }
  245. }
  246. }
  247. public void ToLeftClick()
  248. {
  249. var view = GetView() as DataView;
  250. view.chart.sciChart.ChartModifier.XAxis.Scroll(-50, SciChart.Charting.ClipMode.ClipAtMin);
  251. }
  252. public void ToRightClick()
  253. {
  254. var view = GetView() as DataView;
  255. view.chart.sciChart.ChartModifier.XAxis.Scroll(50, SciChart.Charting.ClipMode.ClipAtMax);
  256. }
  257. public void ZoomInClick()
  258. {
  259. var view = GetView() as DataView;
  260. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(-0.1, -0.1);
  261. view.chart.sciChart.ChartModifier.YAxis.ZoomBy(-0.1, -0.1);
  262. }
  263. public void ZoomOutClick()
  264. {
  265. var view = GetView() as DataView;
  266. view.chart.sciChart.ChartModifier.XAxis.ZoomBy(0.1, 0.1);
  267. view.chart.sciChart.ChartModifier.YAxis.ZoomBy(0.1, 0.1);
  268. }
  269. public void ToMoveUpClick()
  270. {
  271. var view = GetView() as DataView;
  272. view.chart.sciChart.ChartModifier.YAxis.Scroll(-50, SciChart.Charting.ClipMode.ClipAtMin);
  273. }
  274. public void ToMoveDownClick()
  275. {
  276. var view = GetView() as DataView;
  277. view.chart.sciChart.ChartModifier.YAxis.Scroll(50, SciChart.Charting.ClipMode.ClipAtMax);
  278. }
  279. public void Query(object parameter)
  280. {
  281. WaferHistoryRecipe waferHistoryRecipe = parameter as WaferHistoryRecipe;
  282. if (waferHistoryRecipe != null)
  283. {
  284. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  285. {
  286. if (waferHistoryRecipe.StartTime != DateTime.MinValue)
  287. SearchBeginTime = waferHistoryRecipe.StartTime;
  288. if (waferHistoryRecipe.EndTime != DateTime.MinValue)
  289. SearchEndTime = waferHistoryRecipe.EndTime;
  290. else
  291. SearchEndTime = waferHistoryRecipe.StartTime.AddHours(1);
  292. //ParameterNodes.ForEachDo((x) =>
  293. //{
  294. // x.Selected = true;
  295. // ParameterCheck(x);
  296. //});
  297. QueryData();
  298. }));
  299. }
  300. }
  301. /// <summary>
  302. /// 查询数据。
  303. /// </summary>
  304. /// <exception cref="Exception"></exception>
  305. public void QueryData(bool isAppend = false)
  306. {
  307. this.SearchBeginTime = Convert.ToDateTime(this.view.wfTimeFrom.Content);
  308. this.SearchEndTime = Convert.ToDateTime(this.view.wfTimeTo.Content);
  309. if (SearchBeginTime > SearchEndTime)
  310. {
  311. MessageBox.Show("time range invalid, start time should be early than end time.", "Error",
  312. MessageBoxButton.OK,
  313. MessageBoxImage.Error);
  314. return;
  315. }
  316. // 哪些模组(TreeView的顶层Nodes)有选中项。
  317. var selectedModules = ParameterNodes.ChildNodes.Where(x => x.HasTerminalSelected).ToList();
  318. if (!selectedModules.Any())
  319. {
  320. MessageBox.Show($"No item(s) are selected to query.", "Warning", MessageBoxButton.OK,
  321. MessageBoxImage.Warning);
  322. return;
  323. }
  324. VisibleRangeTime = new DateRange(SearchBeginTime.AddHours(-1), SearchEndTime.AddHours(1));
  325. ChartAutoRange = AutoRange.Always;
  326. BusyIndicatorContent = "Preparing list ...";
  327. IsBusy = true;
  328. _cancellationTokenSource = new CancellationTokenSource();
  329. #region 生成曲线列表
  330. var selectedTerminal =
  331. selectedModules.SelectMany(x => x.Flatten(true).Where(p => p.IsSelected == true)).ToList();
  332. List<IRenderableSeries> appendedSeries = null;
  333. if (isAppend)
  334. appendedSeries = SelectedData.Append(selectedTerminal);
  335. else
  336. {
  337. SelectedData.ReArrange(selectedTerminal);
  338. appendedSeries = SelectedData.ToList();
  339. }
  340. SelectedData.ResetColors();
  341. #endregion
  342. var dataSeriesList = appendedSeries.Select(x => x.DataSeries).ToList();
  343. Task.Run(async () =>
  344. {
  345. // 延时启动,等待UI准备好
  346. await Task.Delay(500);
  347. var pipeline = new TwoStagePipelineBasedTaskExecutor<DataSet, object>();
  348. pipeline.Stage2ActionStarted += (s, e) =>
  349. {
  350. // 挂起Chart
  351. _progChartSuspendUpdating.Report(true);
  352. };
  353. pipeline.Stage2ActionFinished += (s, e) =>
  354. {
  355. // 挂起刷新
  356. _progChartSuspendUpdating.Report(false);
  357. };
  358. pipeline.Stage1Finished += (s, e) =>
  359. {
  360. // 查询完毕,Chart可能仍在渲染。
  361. _progQueryUpdate?.Report(new ProgressUpdatingEventArgs(50, 100, "Still rendering chart ..."));
  362. };
  363. using (pipeline)
  364. {
  365. var plTasks = pipeline.Start(null);
  366. try
  367. {
  368. //! 按时间分段查询,解决查询速度慢导致卡后台业务的问题。
  369. var ts = SearchEndTime - SearchBeginTime;
  370. if (ts.Days <= 1)
  371. {
  372. Query(pipeline, selectedModules, dataSeriesList, view.dataGrid1, SearchBeginTime, SearchEndTime,
  373. _cancellationTokenSource, _progQueryUpdate);
  374. // 结束流水线
  375. pipeline.AppendFunc1(null);
  376. pipeline.AppendFunc2(null);
  377. }
  378. else
  379. {
  380. var daySlices =
  381. DateRangeHelper.SplitInToHours(new DateRangeHelper(SearchBeginTime, SearchEndTime), 12);
  382. foreach (var range in daySlices)
  383. {
  384. Query(pipeline, selectedModules, dataSeriesList, view.dataGrid1, range.Start, range.End,
  385. _cancellationTokenSource, _progQueryUpdate);
  386. if (_cancellationTokenSource.Token.IsCancellationRequested)
  387. break;
  388. await Task.Delay(1);
  389. }
  390. // 结束流水线
  391. pipeline.AppendFunc1(null);
  392. pipeline.AppendFunc2(null);
  393. }
  394. await Task.WhenAll(plTasks.ToArray());
  395. }
  396. catch (ThreadAbortException ex)
  397. {
  398. Thread.Sleep(500);
  399. // 查询操作被取消。
  400. Debug.WriteLine(ex);
  401. }
  402. catch (AggregateException ae)
  403. {
  404. var errs = new StringBuilder();
  405. foreach (var ex in ae.Flatten().InnerExceptions)
  406. {
  407. LOG.Error(ex.Message, ex);
  408. errs.AppendLine(ex.Message);
  409. }
  410. var errMsg = $"It's failed to query data, {errs}";
  411. _progShowErrorMessageBox.Report(errMsg);
  412. LOG.Error(errMsg, ae);
  413. }
  414. catch (Exception ex)
  415. {
  416. var errMsg = $"It's failed to query data, {ex.Message}";
  417. _progShowErrorMessageBox.Report(errMsg);
  418. LOG.Error(errMsg, ex);
  419. }
  420. finally
  421. {
  422. // 等待一下UI
  423. Thread.Sleep(100);
  424. _progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  425. // 强制恢复Chart刷新,避免异常情况导致的Chart挂起。
  426. _progChartSuspendUpdating.Report(false);
  427. }
  428. }
  429. });
  430. }
  431. /// <summary>
  432. /// 查询数据
  433. /// </summary>
  434. private static void Query(TwoStagePipelineBasedTaskExecutor<DataSet, object> pipeline, IEnumerable<TreeNode> selectedModules, List<IDataSeries> dataSeriesList, System.Windows.Controls.DataGrid dataGrid, DateTime startTime, DateTime endTime,
  435. CancellationTokenSource cancellation, IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  436. {
  437. pipeline.AppendFunc1(() =>
  438. SearchDataBaseAsync(
  439. selectedModules,
  440. new DateRangeHelper(startTime, endTime),
  441. cancellation,
  442. progressReporter));
  443. pipeline.AppendFunc2(ds =>
  444. {
  445. RenderChartAndTable(ds, dataSeriesList, dataGrid, cancellation, progressReporter);
  446. return null;
  447. });
  448. //pipeline.AppendFunc2(ds =>
  449. //{
  450. // RenderDataGridTable(ds, , cancellation, progressReporter);
  451. // return null;
  452. //});
  453. }
  454. /// <summary>
  455. /// 取消查询。
  456. /// </summary>
  457. public void CancelQuery()
  458. {
  459. Task.Run(() =>
  460. {
  461. if (_cancellationTokenSource?.Token.CanBeCanceled == true)
  462. {
  463. _cancellationTokenSource.Cancel();
  464. }
  465. Thread.Sleep(100);
  466. _progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  467. _progChartSuspendUpdating.Report(false);
  468. });
  469. if (View is DataView view)
  470. view.dataGrid.CancelOperation();
  471. }
  472. /// <summary>
  473. /// 检查指定的表名是否存在。
  474. /// </summary>
  475. /// <param name="tableName"></param>
  476. /// <returns></returns>
  477. private static bool CheckTableExists(string tableName)
  478. {
  479. var sql =
  480. $"SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = '{tableName}' );";
  481. var table = QueryDataClient.Instance.Service.QueryData(sql);
  482. if (table == null)
  483. return false;
  484. if (table.Rows.Count <= 0)
  485. return false;
  486. var value = table.Rows[0][0].ToString();
  487. if (value.ToLower() == "true")
  488. return true;
  489. return false;
  490. }
  491. /// <summary>
  492. /// 根据左侧选项查询数据
  493. /// </summary>
  494. /// <returns></returns>
  495. private static DataSet SearchDataBaseAsync(
  496. IEnumerable<TreeNode> modules, DateRangeHelper dateRange,
  497. CancellationTokenSource cancellation = null,
  498. IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  499. {
  500. var ds = new DataSet();
  501. using (cancellation?.Token.Register(Thread.CurrentThread.Abort, true))
  502. {
  503. // 遍历模组
  504. foreach (var module in modules)
  505. {
  506. var sql = new StringBuilder();
  507. //! 因为数据库中按天拆表,无法一次性查询数据,需使用UNION合并多表查询,因此此处按天拼接SQL表达式
  508. // 最终SQL表达式结构为:
  509. // (select xx from date1.xx) union (select xx from date2.xx) union (select xx from date3.xx)
  510. // where time between xxx and xxx
  511. // order by time asc
  512. var ts = dateRange.Diff;
  513. for (var day = 0; day <= ts.Days; day++)
  514. {
  515. // 检查表名是否存在,否则SQL执行出错。
  516. var tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.{module}";
  517. if (module.ToString() == "IO")
  518. {
  519. //var node = module.ChildNodes.FirstOrDefault(x => (bool)x.HasTerminalSelected);
  520. tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.System";
  521. }
  522. else
  523. if (!ModuleHelper.IsPm(module.ToString()))
  524. {
  525. tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.System";
  526. }
  527. if (CheckTableExists(tblName))
  528. {
  529. sql.Append("select \"time\" AS InternalTimeStamp");
  530. var selectedParams = module.Flatten(true)
  531. .Where(x => x.IsSelected == true);
  532. // 添加待查询的列
  533. foreach (var item in selectedParams)
  534. {
  535. sql.Append("," + $"\"{item}\"");
  536. }
  537. sql.Append($" from \"{tblName}\" ");
  538. if (day < ts.Days)
  539. sql.Append(" UNION ");
  540. }
  541. }
  542. // 所有表名不可用,可能是日期范围错误
  543. if (sql.Length <= 0)
  544. {
  545. continue;
  546. }
  547. sql.Append(
  548. $" where \"time\" between {dateRange.Start.Ticks} and {dateRange.End.Ticks} order by InternalTimeStamp asc");
  549. progressReporter?.Report(new ProgressUpdatingEventArgs(20, 100,
  550. $"Querying {dateRange}..."));
  551. if (cancellation?.Token.IsCancellationRequested == true)
  552. return null;
  553. // 查询数据并将返回的结果存储在DataSet中
  554. var dataTable = QueryDataClient.Instance.Service.QueryData(sql.ToString());
  555. if (cancellation?.Token.IsCancellationRequested == true)
  556. return null;
  557. //! 返回的 DataTable 可能不存在,原因是上述代码自动生成的表明可能不存在。
  558. if (dataTable == null)
  559. continue;
  560. dataTable.TableName = module.Name;
  561. ds.Tables.Add(dataTable);
  562. }
  563. }
  564. return ds;
  565. }
  566. /// <summary>
  567. /// 渲染图表。
  568. /// </summary>
  569. /// <param name="ds"></param>
  570. /// <param name="dataSeriesList"></param>
  571. /// <param name="cancellation"></param>
  572. /// <param name="progressReporter"></param>
  573. /// <exception cref="Exception"></exception>
  574. private static void RenderChartAndTable(
  575. DataSet ds, List<IDataSeries> dataSeriesList, System.Windows.Controls.DataGrid dataGrid,
  576. CancellationTokenSource cancellation = null,
  577. IProgress<ProgressUpdatingEventArgs> progressReporter = null)
  578. {
  579. if (ds == null || ds.Tables.Count <= 0)
  580. return;
  581. Dictionary<string, Dictionary<long, string>> bigTable = new Dictionary<string, Dictionary<long, string>>();
  582. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  583. {
  584. dataGrid.Columns.Clear();
  585. DataGridTextColumn dataGridTextColumn = new DataGridTextColumn();
  586. dataGridTextColumn.Header = "Time";
  587. dataGridTextColumn.Binding = new System.Windows.Data.Binding("internaltimestamp");
  588. ((System.Windows.Data.Binding)dataGridTextColumn.Binding).Converter = new StringToDateTimeStringConvert();
  589. dataGrid.Columns.Add(dataGridTextColumn);
  590. }));
  591. // 一个Table一个模组
  592. foreach (var table in ds.Tables.Cast<DataTable>())
  593. {
  594. if (table.Rows.Count <= 0)
  595. continue;
  596. // 一列对应模组中的某个数据记录点
  597. foreach (var col in table.Columns.Cast<DataColumn>())
  598. {
  599. // 忽略时间列
  600. if (col.Ordinal == 0)
  601. continue;
  602. Dictionary<long, string> dictColumn = new Dictionary<long, string>();
  603. var fullName = col.ColumnName;
  604. col.ColumnName = col.ColumnName.Replace(".", "");
  605. var dataSeries =
  606. dataSeriesList.FirstOrDefault(x => x.SeriesName == fullName) as XyDataSeries<DateTime, double>;
  607. if (dataSeries == null)
  608. continue;
  609. var rows = table.Rows;
  610. var dateList = new List<DateTime>();
  611. var valueList = new List<double>();
  612. var metaList = new List<ParameterNodePoint>();
  613. for (var i = 0; i < rows.Count; i++)
  614. {
  615. var date = new DateTime(long.Parse(rows[i][0].ToString()));
  616. var cellValue = rows[i][col];
  617. var value = double.NaN;
  618. if (cellValue is bool b)
  619. value = b ? 1 : 0;
  620. else if (double.TryParse(cellValue.ToString(), out var num))
  621. value = num;
  622. else
  623. value = 0;
  624. dateList.Add(date);
  625. valueList.Add(value);
  626. metaList.Add(new ParameterNodePoint(date, value));
  627. dictColumn.Add(long.Parse(rows[i][0].ToString()), value.ToString());
  628. if (cancellation?.Token.IsCancellationRequested == true)
  629. return;
  630. }
  631. bigTable.Add(fullName.Replace(".", ""), dictColumn);
  632. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  633. {
  634. DataGridTextColumn dataGridTextColumn2 = new DataGridTextColumn();
  635. dataGridTextColumn2.Header = fullName;
  636. dataGridTextColumn2.Binding = new System.Windows.Data.Binding(fullName.Replace(".", ""));
  637. var MyStyle = new Style(typeof(DataGridCell))
  638. {
  639. Setters = {
  640. new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
  641. }
  642. };
  643. dataGridTextColumn2.CellStyle = MyStyle;
  644. dataGrid.Columns.Add(dataGridTextColumn2);
  645. }));
  646. if (cancellation?.Token.IsCancellationRequested == true)
  647. return;
  648. dataSeries.Append(dateList, valueList, metaList);
  649. }
  650. if (cancellation?.Token.IsCancellationRequested == true)
  651. return;
  652. // 每一轮更新完毕后会恢复Chart刷新,
  653. // 数据量太小时会频繁挂起和恢复Chart,导致Chart不刷新,需要稍等一下UI。
  654. Thread.Sleep(50);
  655. }
  656. System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  657. {
  658. System.Data.DataTable dt = new System.Data.DataTable();
  659. dt = new System.Data.DataTable($"Temp");
  660. dt.Columns.Add("internaltimestamp", typeof(long));
  661. foreach (var item in bigTable.Keys)
  662. {
  663. dt.Columns.Add(item, typeof(string));
  664. }
  665. if (bigTable.Count > 0)
  666. {
  667. foreach (var subitem in bigTable[bigTable.FirstOrDefault().Key].Keys)
  668. {
  669. var row = dt.NewRow();
  670. row[0] = subitem;
  671. foreach (var col in bigTable.Keys)
  672. {
  673. row[col] = bigTable[col][subitem];
  674. }
  675. dt.Rows.Add(row);
  676. }
  677. }
  678. dataGrid.ItemsSource = dt.DefaultView;
  679. }));
  680. }
  681. public void Exporting(object sender, EventArgs e)
  682. {
  683. BusyIndicatorContent = "Exporting Start ...";
  684. IsBusy = true;
  685. }
  686. public void Exported(object sender, EventArgs e)
  687. {
  688. IsBusy = false;
  689. }
  690. public void Deleted(object sender, EventArgs e)
  691. {
  692. ((DataView)View).tvParameterNodes.ClearPresetGroupSelectionOnly();
  693. }
  694. public void ProgressUpdating(object sender, ProgressUpdatingEventArgs e)
  695. {
  696. _progCsvExport.Report(e);
  697. }
  698. #endregion
  699. }
  700. public class StringToDateTimeStringConvert : IValueConverter
  701. {
  702. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  703. {
  704. return new DateTime((Int64)value).ToString("yyyy/MM/dd HH:mm:ss");
  705. }
  706. public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
  707. {
  708. return null;
  709. }
  710. }
  711. }