DataViewModel.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Windows;
  8. using Aitex.Core.RT.Log;
  9. using Aitex.Core.UI.ControlDataContext;
  10. using Aitex.Core.Util;
  11. using Aitex.Sorter.Common;
  12. using MECF.Framework.Common.CommonData;
  13. using MECF.Framework.Common.ControlDataContext;
  14. using MECF.Framework.Common.DataCenter;
  15. using MECF.Framework.Common.Utilities;
  16. using OpenSEMI.ClientBase;
  17. using SciChart.Charting.Visuals.Axes;
  18. using SciChart.Charting.Visuals.RenderableSeries;
  19. using SciChart.Data.Model;
  20. using VirgoUI.Client.Models.History.ProcessHistory;
  21. using VirgoUI.Client.Models.Operate.RealTime;
  22. using VirgoUI.Client.Models.Sys;
  23. namespace VirgoUI.Client.Models.History.DataHistory
  24. {
  25. public class TimeChartDataLine : ChartDataLine
  26. {
  27. public string Module { get; set; }
  28. public DateTime StartTime { get; set; }
  29. public DateTime EndTime { get; set; }
  30. public DateTime TokenTime { get; set; }
  31. private string[] _dbModules = {"PM2", "PM4", "PM6"};
  32. public TimeChartDataLine(string dataName, DateTime startTime, DateTime endTime) : base(dataName)
  33. {
  34. StartTime = startTime;
  35. EndTime = endTime;
  36. TokenTime = startTime;
  37. Module = "System";
  38. foreach (var dbModule in _dbModules)
  39. {
  40. if (dataName.StartsWith(dbModule))
  41. {
  42. Module = dbModule;
  43. break;
  44. }
  45. }
  46. }
  47. }
  48. public class DataViewModel : UiViewModelBase
  49. {
  50. private int MenuPermission;
  51. private class QueryIndexer
  52. {
  53. public DateTime TimeToken { get; set; }
  54. public List<string> DataList { get; set; }
  55. public string Module { get; set; }
  56. }
  57. #region Property
  58. private const int MAX_PARAMETERS = 20;
  59. private ObservableCollection<ParameterNode> _ParameterNodes;
  60. public ObservableCollection<ParameterNode> ParameterNodes
  61. {
  62. get { return _ParameterNodes; }
  63. set { _ParameterNodes = value; NotifyOfPropertyChange("ParameterNodes"); }
  64. }
  65. public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  66. private object _lockSelection = new object();
  67. private object _lockQueryCondition = new object();
  68. private AutoRange _autoRange;
  69. public AutoRange ChartAutoRange
  70. {
  71. get { return _autoRange; }
  72. set
  73. {
  74. _autoRange = value;
  75. NotifyOfPropertyChange(nameof(ChartAutoRange));
  76. }
  77. }
  78. private IRange _timeRange;
  79. public IRange VisibleRangeTime
  80. {
  81. get { return _timeRange; }
  82. set
  83. {
  84. _timeRange = value;
  85. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  86. }
  87. }
  88. private IRange _VisibleRangeValue;
  89. public IRange VisibleRangeValue
  90. {
  91. get { return _VisibleRangeValue; }
  92. set { _VisibleRangeValue = value; NotifyOfPropertyChange(nameof(VisibleRangeValue)); }
  93. }
  94. public DateTime StartDateTime { get; set; }
  95. public DateTime EndDateTime { get; set; }
  96. public DateTime _queryDateTimeToken;
  97. //private bool _restart;
  98. private PeriodicJob _thread;
  99. ConcurrentBag<QueryIndexer> _lstTokenTimeData = new ConcurrentBag<QueryIndexer>();
  100. RealtimeProvider _provider = new RealtimeProvider();
  101. #endregion
  102. #region Function
  103. public DataViewModel()
  104. {
  105. MenuPermission = ClientApp.Instance.GetPermission("DataHistory");
  106. DisplayName = "Data History";
  107. SelectedData = new ObservableCollection<IRenderableSeries>();
  108. ParameterNodes = _provider.GetParameters();
  109. var now = DateTime.Now;
  110. StartDateTime = now.AddHours(-2);
  111. EndDateTime = now;
  112. _queryDateTimeToken = StartDateTime;
  113. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(60), DateTime.Now.AddMinutes(-60));
  114. VisibleRangeValue = new DoubleRange(0, 10);
  115. _thread = new PeriodicJob(500, MonitorData, "RealTime", true);
  116. }
  117. protected override void OnActivate()
  118. {
  119. base.OnActivate();
  120. }
  121. protected bool MonitorData()
  122. {
  123. try
  124. {
  125. bool allUpdated = true;
  126. lock (_lockSelection)
  127. {
  128. foreach (var item in _lstTokenTimeData)
  129. {
  130. DateTime timeFrom = item.TimeToken;
  131. if (timeFrom >= EndDateTime)
  132. continue;
  133. allUpdated = false;
  134. Application.Current.Dispatcher.BeginInvoke(new Action(() => { ChartAutoRange = AutoRange.Always; }));
  135. DateTime timeTo = timeFrom.AddMinutes(60);
  136. if (timeTo > EndDateTime)
  137. timeTo = EndDateTime;
  138. item.TimeToken = timeTo;
  139. GetData(item.DataList, timeFrom, timeTo, item.Module);
  140. }
  141. }
  142. if (allUpdated)
  143. {
  144. lock (_lockSelection)
  145. {
  146. while (_lstTokenTimeData.Count > 0)
  147. {
  148. _lstTokenTimeData.TryTake(out _);
  149. }
  150. }
  151. Application.Current.Dispatcher.BeginInvoke(new Action(() => { ChartAutoRange = AutoRange.Never; }));
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. LOG.Error(ex.Message);
  157. }
  158. return true;
  159. }
  160. public void Preset()
  161. {
  162. }
  163. public void Clear()
  164. {
  165. }
  166. private void GetData(List<string> keys, DateTime from, DateTime to, string module)
  167. {
  168. string sql = "select time AS InternalTimeStamp";
  169. foreach (var dataId in keys)
  170. {
  171. sql += "," + string.Format("\"{0}\"", dataId);
  172. }
  173. sql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  174. from.ToString("yyyyMMdd") + "." + "Data", from.Ticks, to.Ticks);
  175. DataTable dataTable = QueryDataClient.Instance.Service.QueryData(sql);
  176. Dictionary<string, List<HistoryDataItem>> historyData = new Dictionary<string, List<HistoryDataItem>>();
  177. if (dataTable == null || dataTable.Rows.Count == 0)
  178. return;
  179. DateTime dt = new DateTime();
  180. Dictionary<int, string> colName = new Dictionary<int, string>();
  181. for (int colNo = 0; colNo < dataTable.Columns.Count; colNo++)
  182. {
  183. colName.Add(colNo, dataTable.Columns[colNo].ColumnName);
  184. historyData[dataTable.Columns[colNo].ColumnName] = new List<HistoryDataItem>();
  185. }
  186. for (int rowNo = 0; rowNo < dataTable.Rows.Count; rowNo++)
  187. {
  188. var row = dataTable.Rows[rowNo];
  189. for (int i = 0; i < dataTable.Columns.Count; i++)
  190. {
  191. HistoryDataItem data = new HistoryDataItem();
  192. if (i == 0)
  193. {
  194. long ticks = (long)row[i];
  195. dt = new DateTime(ticks);
  196. continue;
  197. }
  198. else
  199. {
  200. string dataId = colName[i];
  201. if (row[i] is DBNull || row[i] == null)
  202. {
  203. data.dateTime = dt;
  204. data.dbName = colName[i];
  205. data.value = 0;
  206. }
  207. else if (row[i] is bool)
  208. {
  209. data.dateTime = dt;
  210. data.dbName = colName[i];
  211. data.value = (bool)row[i] ? 1 : 0;
  212. }
  213. else
  214. {
  215. data.dateTime = dt;
  216. data.dbName = colName[i];
  217. data.value = float.Parse(row[i].ToString());
  218. }
  219. }
  220. historyData[data.dbName].Add(data);
  221. }
  222. }
  223. Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  224. {
  225. try
  226. {
  227. double min = ((DoubleRange)VisibleRangeValue).Min ;
  228. double max = ((DoubleRange)VisibleRangeValue).Max;
  229. foreach (var data in historyData)
  230. {
  231. foreach (var item in SelectedData)
  232. {
  233. var seriesItem = item as ChartDataLine;
  234. if (data.Key != seriesItem.DataName)
  235. continue;
  236. foreach (var historyDataItem in data.Value)
  237. {
  238. if (historyDataItem.value < min)
  239. min = historyDataItem.value;
  240. if (historyDataItem.value > max)
  241. max = historyDataItem.value;
  242. seriesItem.Append(historyDataItem.dateTime, historyDataItem.value);
  243. }
  244. }
  245. }
  246. VisibleRangeTime = new DateRange(StartDateTime.AddMinutes(-5), EndDateTime.AddMinutes(5));
  247. VisibleRangeValue = new DoubleRange(min,max);
  248. }
  249. catch (Exception ex)
  250. {
  251. LOG.Write(ex);
  252. }
  253. }));
  254. }
  255. private DataView view;
  256. public void Query()
  257. {
  258. if (MenuPermission != 3) return;
  259. this.StartDateTime = this.view.wfTimeFrom.Value;
  260. this.EndDateTime = this.view.wfTimeTo.Value;
  261. if (StartDateTime > EndDateTime)
  262. {
  263. MessageBox.Show("Time range invalid, start time should be early than end time");
  264. return;
  265. }
  266. ParameterNodes = _provider.GetParameters();
  267. VisibleRangeTime = new DateRange(StartDateTime.AddMinutes(-5), EndDateTime.AddMinutes(5));
  268. ChartAutoRange = AutoRange.Always;
  269. lock (_lockQueryCondition)
  270. {
  271. _queryDateTimeToken = StartDateTime;
  272. //_restart = true;
  273. while (!_lstTokenTimeData.IsEmpty)
  274. {
  275. _lstTokenTimeData.TryTake(out _);
  276. }
  277. foreach (var dataLine in SelectedData)
  278. {
  279. TimeChartDataLine line = dataLine as TimeChartDataLine;
  280. line.ClearData();
  281. QueryIndexer indexer = _lstTokenTimeData.FirstOrDefault(x => x.Module == line.Module);
  282. if (indexer == null)
  283. {
  284. indexer = new QueryIndexer()
  285. {
  286. DataList = new List<string>(),
  287. Module = line.Module,
  288. TimeToken = StartDateTime,
  289. };
  290. _lstTokenTimeData.Add(indexer);
  291. }
  292. indexer.DataList.Add(line.DataName);
  293. }
  294. }
  295. }
  296. public void Query(object parameter)
  297. {
  298. WaferHistoryRecipe waferHistoryRecipe = parameter as WaferHistoryRecipe;
  299. if (waferHistoryRecipe != null)
  300. {
  301. Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  302. {
  303. if (waferHistoryRecipe.StartTime != DateTime.MinValue)
  304. this.view.wfTimeFrom.Value = waferHistoryRecipe.StartTime;
  305. if (waferHistoryRecipe.EndTime != DateTime.MinValue)
  306. this.view.wfTimeTo.Value = waferHistoryRecipe.EndTime;
  307. else
  308. this.view.wfTimeTo.Value = waferHistoryRecipe.StartTime.AddHours(1);
  309. //ParameterNodes.ForEachDo((x) =>
  310. //{
  311. // x.Selected = true;
  312. // ParameterCheck(x);
  313. //});
  314. Query();
  315. }));
  316. }
  317. }
  318. public void ParameterCheck(ParameterNode node)
  319. {
  320. bool result = RefreshTreeStatusToChild(node);
  321. if (!result)
  322. node.Selected = !node.Selected;
  323. else
  324. RefreshTreeStatusToParent(node);
  325. }
  326. /// <summary>
  327. /// Refresh tree node status from current to children, and add data to SelectedData
  328. /// </summary>
  329. private bool RefreshTreeStatusToChild(ParameterNode node)
  330. {
  331. if (node.ChildNodes.Count > 0)
  332. {
  333. for (int i = 0; i < node.ChildNodes.Count; i++)
  334. {
  335. ParameterNode n = node.ChildNodes[i];
  336. n.Selected = node.Selected;
  337. if (!RefreshTreeStatusToChild(n))
  338. {
  339. //uncheck left node
  340. for (int j = i; j < node.ChildNodes.Count; j++)
  341. {
  342. node.ChildNodes[j].Selected = !node.Selected;
  343. }
  344. node.Selected = !node.Selected;
  345. return false;
  346. }
  347. }
  348. }
  349. else //leaf node
  350. {
  351. lock (_lockSelection)
  352. {
  353. bool isExist = SelectedData.FirstOrDefault(x => (x as ChartDataLine).DataName == node.Name) != null;
  354. if (node.Selected && !isExist)
  355. {
  356. if (SelectedData.Count < MAX_PARAMETERS)
  357. {
  358. var line = new TimeChartDataLine(node.Name, StartDateTime, EndDateTime);
  359. line.Tag = node;
  360. SelectedData.Add(line);
  361. QueryIndexer indexer = _lstTokenTimeData.FirstOrDefault(x => x.Module == line.Module);
  362. if (indexer == null)
  363. {
  364. indexer = new QueryIndexer()
  365. {
  366. DataList = new List<string>(),
  367. Module = line.Module,
  368. TimeToken = StartDateTime,
  369. };
  370. _lstTokenTimeData.Add(indexer);
  371. }
  372. indexer.DataList.Add(line.DataName);
  373. }
  374. else
  375. {
  376. DialogBox.ShowWarning($"The max number of parameters is {MAX_PARAMETERS}.");
  377. return false;
  378. }
  379. }
  380. else if (!node.Selected && isExist)
  381. {
  382. //SelectedParameters.Remove(node.Name);
  383. var data = SelectedData.FirstOrDefault(d => (d as ChartDataLine).DataName == node.Name);
  384. SelectedData.Remove(data);
  385. }
  386. }
  387. }
  388. return true;
  389. }
  390. /// <summary>
  391. /// Refresh tree node status from current to parent
  392. /// </summary>
  393. /// <param name="node"></param>
  394. /// <returns></returns>
  395. private void RefreshTreeStatusToParent(ParameterNode node)
  396. {
  397. if (node.ParentNode != null)
  398. {
  399. if (node.Selected)
  400. {
  401. bool flag = true;
  402. for (int i = 0; i < node.ParentNode.ChildNodes.Count; i++)
  403. {
  404. if (!node.ParentNode.ChildNodes[i].Selected)
  405. {
  406. flag = false; //as least one child is unselected
  407. break;
  408. }
  409. }
  410. if (flag)
  411. node.ParentNode.Selected = true;
  412. }
  413. else
  414. {
  415. node.ParentNode.Selected = false;
  416. }
  417. RefreshTreeStatusToParent(node.ParentNode);
  418. }
  419. }
  420. #region Parameter Grid Control
  421. public void DeleteAll()
  422. {
  423. if (MenuPermission != 3) return;
  424. //uncheck all tree nodes
  425. foreach (ChartDataLine cp in SelectedData)
  426. {
  427. (cp.Tag as ParameterNode).Selected = false;
  428. RefreshTreeStatusToParent(cp.Tag as ParameterNode);
  429. }
  430. SelectedData.Clear();
  431. }
  432. private void SetParameterNode(ObservableCollection<ParameterNode> nodes, bool isChecked)
  433. {
  434. foreach (ParameterNode n in nodes)
  435. {
  436. n.Selected = isChecked;
  437. SetParameterNode(n.ChildNodes, isChecked);
  438. }
  439. }
  440. public void Delete(ChartDataLine cp)
  441. {
  442. if (MenuPermission != 3) return;
  443. if (cp != null && SelectedData.Contains(cp))
  444. {
  445. //uncheck tree node
  446. (cp.Tag as ParameterNode).Selected = false;
  447. RefreshTreeStatusToParent(cp.Tag as ParameterNode);
  448. SelectedData.Remove(cp);
  449. }
  450. }
  451. public void ExportAll()
  452. {
  453. if (MenuPermission != 3) return;
  454. try
  455. {
  456. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  457. dlg.DefaultExt = ".xlsx"; // Default file extension
  458. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  459. dlg.FileName = $"Export_{DateTime.Now:yyyyMMdd_HHmmss}";
  460. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  461. if (result == true) // Process open file dialog box results
  462. {
  463. System.Data.DataSet ds = new System.Data.DataSet();
  464. ds.Tables.Add(new System.Data.DataTable($"Export_{DateTime.Now:yyyyMMdd_HHmmss}"));
  465. ds.Tables[0].Columns.Add("Time");
  466. ds.Tables[0].Columns[0].DataType = typeof(DateTime);
  467. lock (_lockSelection)
  468. {
  469. Dictionary<DateTime, double[]> timeValue = new Dictionary<DateTime, double[]>();
  470. for (int i = 0; i < SelectedData.Count; i++)
  471. {
  472. List<Tuple<DateTime, double>> data = (SelectedData[i] as ChartDataLine).Points;
  473. foreach (var tuple in data)
  474. {
  475. if (!timeValue.ContainsKey(tuple.Item1))
  476. timeValue[tuple.Item1] = new double[SelectedData.Count];
  477. timeValue[tuple.Item1][i] = tuple.Item2;
  478. }
  479. ds.Tables[0].Columns.Add((SelectedData[i] as ChartDataLine).DataName);
  480. ds.Tables[0].Columns[i + 1].DataType = typeof(double);
  481. }
  482. foreach (var item in timeValue)
  483. {
  484. var row = ds.Tables[0].NewRow();
  485. row[0] = item.Key;
  486. for (int j = 0; j < item.Value.Length; j++)
  487. {
  488. row[j + 1] = item.Value[j];
  489. }
  490. ds.Tables[0].Rows.Add(row);
  491. }
  492. }
  493. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  494. {
  495. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  496. return;
  497. }
  498. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  499. }
  500. }
  501. catch (Exception ex)
  502. {
  503. LOG.Write(ex);
  504. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  505. }
  506. }
  507. public void Export(ChartDataLine cp)
  508. {
  509. if (MenuPermission != 3) return;
  510. try
  511. {
  512. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  513. dlg.DefaultExt = ".xlsx"; // Default file extension
  514. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  515. dlg.FileName = $"{cp.DataName}_{DateTime.Now:yyyyMMdd_HHmmss}";
  516. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  517. if (result == true) // Process open file dialog box results
  518. {
  519. System.Data.DataSet ds = new System.Data.DataSet();
  520. ds.Tables.Add(new System.Data.DataTable(cp.DataName));
  521. ds.Tables[0].Columns.Add("Time");
  522. ds.Tables[0].Columns[0].DataType = typeof(DateTime);
  523. ds.Tables[0].Columns.Add(cp.DataName);
  524. ds.Tables[0].Columns[1].DataType = typeof(double);
  525. foreach (var item in cp.Points)
  526. {
  527. var row = ds.Tables[0].NewRow();
  528. row[0] = item.Item1;
  529. row[1] = item.Item2;
  530. ds.Tables[0].Rows.Add(row);
  531. }
  532. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  533. {
  534. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  535. return;
  536. }
  537. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  538. }
  539. }
  540. catch (Exception ex)
  541. {
  542. LOG.Write(ex);
  543. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  544. }
  545. }
  546. public void SelectColor(ChartDataLine cp)
  547. {
  548. if (cp == null)
  549. return;
  550. var dlg = new System.Windows.Forms.ColorDialog();
  551. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  552. {
  553. cp.Stroke = new System.Windows.Media.Color() { A = dlg.Color.A, B = dlg.Color.B, G = dlg.Color.G, R = dlg.Color.R };
  554. }
  555. }
  556. #endregion
  557. #endregion
  558. protected override void OnViewLoaded(object _view)
  559. {
  560. base.OnViewLoaded(_view);
  561. this.view = (DataView)_view;
  562. this.view.wfTimeFrom.Value = this.StartDateTime;
  563. this.view.wfTimeTo.Value = this.EndDateTime;
  564. //this.AppendData();
  565. }
  566. }
  567. }