DataViewModel.cs 24 KB

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