DataViewModel.cs 22 KB

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