ProcessExportAllViewModel.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. using Aitex.Core.RT.Log;
  2. using Aitex.Core.UI.ControlDataContext;
  3. using Aitex.Core.Util;
  4. using Caliburn.Micro;
  5. using Caliburn.Micro.Core;
  6. using MECF.Framework.Common.CommonData;
  7. using MECF.Framework.Common.ControlDataContext;
  8. using MECF.Framework.Common.DataCenter;
  9. using MECF.Framework.Common.Utilities;
  10. using MECF.Framework.UI.Client.CenterViews.Configs.SystemConfig;
  11. using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
  12. using MECF.Framework.UI.Client.CenterViews.Dialogs;
  13. using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
  14. using MECF.Framework.UI.Client.ClientBase;
  15. using OpenSEMI.ClientBase;
  16. using SciChart.Charting.Visuals;
  17. using SciChart.Charting.Visuals.Annotations;
  18. using SciChart.Charting.Visuals.Axes;
  19. using SciChart.Charting.Visuals.RenderableSeries;
  20. using SciChart.Data.Model;
  21. using System;
  22. using System.Collections.Concurrent;
  23. using System.Collections.Generic;
  24. using System.Collections.ObjectModel;
  25. using System.Data;
  26. using System.Diagnostics;
  27. using System.Drawing;
  28. using System.Linq;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using System.Windows;
  33. using static MECF.Framework.Common.FAServices.DataVariables;
  34. using Action = System.Action;
  35. using Media = System.Windows.Media;
  36. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory
  37. {
  38. class ProcessExportAllViewModel<T> : ModuleUiViewModelBase where T : IComparable
  39. {
  40. private ProcessExportAllView view;
  41. private CancellationTokenSource _cancellationTokenSource;
  42. private event EventHandler Exporting;
  43. private const int MAX_PARAMETERS = 1000;
  44. public List<ProcessHistoryLot> RecipeDatas { get; set; }
  45. private ObservableCollection<ParameterNode> _ParameterNodes;
  46. public ObservableCollection<ParameterNode> ParameterNodes
  47. {
  48. get { return _ParameterNodes; }
  49. set { _ParameterNodes = value; NotifyOfPropertyChange("ParameterNodes"); }
  50. }
  51. private Dictionary<string, string> _processDetailDisplayDic = new Dictionary<string, string>();
  52. private Dictionary<string, Dictionary<string, string>> _processProcessDetailAttributeDict = new Dictionary<string, Dictionary<string, string>>();
  53. // public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  54. public ObservableCollection<ParameterNode> GetParameters()
  55. {
  56. ObservableCollection<ParameterNode> rootNode = new ObservableCollection<ParameterNode>();
  57. try
  58. {
  59. Dictionary<string, string> displayDic = QueryDataClient.Instance.Service.GetData("System.ProcessDetailDisplay") as Dictionary<string, string>;
  60. if (displayDic == null)
  61. return rootNode;
  62. List<string> dataList = new List<string>();
  63. foreach (var key in displayDic.Keys)
  64. {
  65. string[] item = key.Split('.');
  66. if (item != null)
  67. {
  68. if (item.Length == 2)
  69. {
  70. _processDetailDisplayDic.Add($"{item[1]}", displayDic[key]);
  71. dataList.Add($"{item[0]}.{item[1]}");
  72. }
  73. else if (item.Length == 3)
  74. {
  75. _processDetailDisplayDic.Add($"{item[1]} {item[2]}", displayDic[key]);
  76. dataList.Add($"{item[0]}.{item[1]}.{item[2]}");
  77. }
  78. }
  79. Dictionary<string, ParameterNode> indexer = new Dictionary<string, ParameterNode>();
  80. foreach (string dataName in dataList)
  81. {
  82. string[] nodeName = dataName.Split('.');
  83. ParameterNode parentNode = null;
  84. string pathName = "";
  85. for (int i = 0; i < nodeName.Length; i++)
  86. {
  87. pathName = (i == 0 || i == 1) ? nodeName[i] : (pathName + " " + nodeName[i]);
  88. if (!indexer.ContainsKey(pathName))
  89. {
  90. indexer[pathName] = new ParameterNode() { Name = pathName, ChildNodes = new ObservableCollection<ParameterNode>(), ParentNode = parentNode };
  91. if (parentNode == null)
  92. {
  93. rootNode.Add(indexer[pathName]);
  94. }
  95. else
  96. {
  97. parentNode.ChildNodes.Add(indexer[pathName]);
  98. }
  99. }
  100. parentNode = indexer[pathName];
  101. }
  102. }
  103. SortParameterNode(rootNode, "Heater", 0);
  104. SortParameterNode(rootNode, "MFC", 1);
  105. SortParameterNode(rootNode, "Pressure", 2);
  106. SortParameterNode(rootNode, "Boat", 3);
  107. SortParameterNode(rootNode, "HeaterBand", 4);
  108. SortParameterNode(rootNode, "Valve", 5);
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. LOG.Write(ex);
  114. }
  115. return rootNode;
  116. }
  117. void SortParameterNode(ObservableCollection<ParameterNode> rootNode, string Name, int Index)
  118. {
  119. if (rootNode[Index].Name != Name)
  120. {
  121. for (int i = 0; i < rootNode.Count; i++)
  122. {
  123. rootNode[i].Selected = true;
  124. if (rootNode[i].Name == Name)
  125. {
  126. ParameterNode node = rootNode[i];
  127. rootNode.RemoveAt(i);
  128. rootNode.Insert(Index, node);
  129. }
  130. }
  131. }
  132. }
  133. private IRange _timeRange;
  134. public IRange VisibleRangeTime
  135. {
  136. get { return _timeRange; }
  137. set
  138. {
  139. _timeRange = value;
  140. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  141. }
  142. }
  143. private IRange _VisibleRangeValue;
  144. public IRange VisibleRangeValue
  145. {
  146. get { return _VisibleRangeValue; }
  147. set { _VisibleRangeValue = value; NotifyOfPropertyChange(nameof(VisibleRangeValue)); }
  148. }
  149. private AnnotationCollection _annotations;
  150. public AnnotationCollection Annotations
  151. {
  152. get => _annotations;
  153. set
  154. {
  155. _annotations = value;
  156. InvokePropertyChanged(nameof(Annotations));
  157. }
  158. }
  159. //private PeriodicJob _thread;
  160. private List<StepInfo> _stepInfo = new List<StepInfo>();
  161. public List<StepInfo> StepInfo
  162. {
  163. get { return _stepInfo; }
  164. set { _stepInfo = value; this.NotifyOfPropertyChange(nameof(StepInfo)); }
  165. }
  166. private bool _isBusy = false;
  167. private string _busyIndicatorMessage;
  168. /// <summary>
  169. /// 设置或返回忙信息。
  170. /// </summary>
  171. public string BusyIndicatorContent
  172. {
  173. get => _busyIndicatorMessage;
  174. set
  175. {
  176. _busyIndicatorMessage = value;
  177. NotifyOfPropertyChange(nameof(BusyIndicatorContent));
  178. }
  179. }
  180. /// <summary>
  181. /// 设置或返回视图是否正忙。
  182. /// </summary>
  183. public bool IsBusy
  184. {
  185. get => _isBusy;
  186. set
  187. {
  188. _isBusy = value;
  189. NotifyOfPropertyChange(nameof(IsBusy));
  190. }
  191. }
  192. private RealtimeProvider _realtimeProvider;
  193. public ProcessExportAllViewModel(List<ProcessHistoryLot> recipes)
  194. {
  195. DisplayName = "Process Export";
  196. RecipeDatas = recipes;
  197. _realtimeProvider = new RealtimeProvider();
  198. ParameterNodes = _realtimeProvider.GetParameters(out var dict, true);
  199. _processDetailDisplayDic = dict;
  200. _processProcessDetailAttributeDict = _realtimeProvider.GetProcessProcessDetailAttributeDict();
  201. if (recipes == null || recipes.Count == 0)
  202. {
  203. return;
  204. }
  205. //SelectedData = new ObservableCollection<IRenderableSeries>();
  206. var now = DateTime.Now;
  207. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(60), DateTime.Now.AddMinutes(-60));
  208. VisibleRangeValue = new DoubleRange(0, 10);
  209. Annotations = new AnnotationCollection();
  210. // _thread = new PeriodicJob(200, MonitorData, "ProcessExport", true);
  211. RecipeDatas.ToList().ForEach(recipe =>
  212. {
  213. QueryStep(recipe.StartTime, recipe.EndTime);
  214. });
  215. if (StepInfo != null && StepInfo.Count > 0)
  216. {
  217. StepStartTime = StepInfo.FirstOrDefault().StartTime;
  218. StepEndTime = StepInfo.LastOrDefault().EndTime;
  219. }
  220. else
  221. {
  222. if (recipes.Count > 0)
  223. {
  224. StepStartTime = recipes[0].StartTime;
  225. StepEndTime = recipes[0].EndTime;
  226. }
  227. }
  228. }
  229. public bool IsStepVisiable => RecipeDatas.Count == 1;
  230. public DateTime StepStartTime { get; set; }
  231. public DateTime StepEndTime { get; set; }
  232. private bool _isAdding;
  233. private static object _lockSelection = new object();
  234. private ConcurrentBag<QueryIndexer> _lstTokenTimeData = new ConcurrentBag<QueryIndexer>();
  235. public class QueryIndexer
  236. {
  237. public TimeChartDataLine DataLine { get; set; }
  238. public List<string> DataList { get; set; }
  239. public DateTime TimeToken { get; set; }
  240. }
  241. public class TimeChartDataLine : ChartDataLine<T>
  242. {
  243. public string Module { get; set; }
  244. public DateTime StartTime { get; set; }
  245. public DateTime EndTime { get; set; }
  246. public TimeChartDataLine(string dataName, string module, DateTime startTime, DateTime endTime) : base(dataName)
  247. {
  248. StartTime = startTime;
  249. EndTime = endTime;
  250. Module = module;
  251. }
  252. }
  253. private string _resolution;
  254. private AutoRange _autoRange;
  255. public AutoRange ChartAutoRange
  256. {
  257. get { return _autoRange; }
  258. set
  259. {
  260. _autoRange = value;
  261. NotifyOfPropertyChange(nameof(ChartAutoRange));
  262. }
  263. }
  264. public void QueryStep(DateTime starTime, DateTime endTime)//, string recipeName去掉查询recipeName名称,有嵌套调用
  265. {
  266. starTime = starTime.AddMinutes(-1);
  267. endTime = endTime.AddMinutes(1);
  268. string sql = $"SELECT * FROM \"process_data\" where (\"process_begin_time\" >= '{starTime:yyyy/MM/dd HH:mm:ss.fff}' and \"process_end_time\" <= '{endTime:yyyy/MM/dd HH:mm:ss.fff}') order by \"process_begin_time\" DESC;";
  269. DataTable dbData = QueryDataClient.Instance.Service.QueryData(sql);
  270. if (dbData != null && dbData.Rows.Count > 0)
  271. {
  272. List<ProcessDataLot> ProcessDataLotList = new List<ProcessDataLot>();
  273. for (int i = 0; i < dbData.Rows.Count; i++)
  274. {
  275. ProcessDataLot item = new ProcessDataLot();
  276. item.GUID = dbData.Rows[i]["guid"].ToString();
  277. item.RecipeName = dbData.Rows[i]["recipe_name"].ToString();
  278. item.ProcessStatus = dbData.Rows[i]["process_status"].ToString();
  279. item.WaferDataGUID = dbData.Rows[i]["wafer_data_guid"].ToString();
  280. item.ProcessIn = dbData.Rows[i]["process_in"].ToString();
  281. if (!dbData.Rows[i]["process_begin_time"].Equals(DBNull.Value))
  282. {
  283. item.ProcessBeginTime = (DateTime)dbData.Rows[i]["process_begin_time"];
  284. }
  285. if (!dbData.Rows[i]["process_end_time"].Equals(DBNull.Value))
  286. {
  287. item.ProcessEndTime = (DateTime)dbData.Rows[i]["process_end_time"];
  288. }
  289. ProcessDataLotList.Add(item);
  290. }
  291. // Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessBeginTime, Media.Brushes.Blue, $"{ProcessDataLotList[0].RecipeName}"));
  292. //Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessEndTime, Media.Brushes.Blue, $"Recipe End"));
  293. string sql2 = $"SELECT * FROM \"recipe_step_data\" where";
  294. sql2 += $" \"recipe_step_data\".\"process_data_guid\" = '{ProcessDataLotList[0].GUID.ToString()}'";
  295. sql2 += " order by \"step_begin_time\" ASC;";
  296. using (var table = QueryDataClient.Instance.Service.QueryData(sql2))
  297. {
  298. if (!(table == null || table.Rows.Count == 0))
  299. {
  300. for (int i = 0; i < table.Rows.Count; i++)
  301. {
  302. var item = table.Rows[i];
  303. string startStepTime = "";
  304. string endStepTime = "";
  305. double stepTime = 0;
  306. string subRecipeStepNumber = "";
  307. string subRecipeStepTime = "";
  308. string subRecipeStepName = "";
  309. string subRecipeLoopInfo = "";
  310. string tempCorrection = "";
  311. string tempPid = "";
  312. if (!item["step_begin_time"].Equals(DBNull.Value))
  313. startStepTime = ((DateTime)item["step_begin_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  314. if (!item["step_end_time"].Equals(DBNull.Value))
  315. {
  316. endStepTime = ((DateTime)item["step_end_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  317. }
  318. if (!item["step_time"].Equals(DBNull.Value))
  319. {
  320. stepTime = (float)item["step_time"];
  321. }
  322. if (!item["sub_recipe_step_time"].Equals(DBNull.Value))
  323. {
  324. subRecipeStepTime = item["sub_recipe_step_time"].ToString();
  325. }
  326. if (!item["sub_recipe_step_number"].Equals(DBNull.Value))
  327. {
  328. subRecipeStepNumber = item["sub_recipe_step_number"].ToString();
  329. }
  330. if (!item["sub_recipe_step_name"].Equals(DBNull.Value))
  331. {
  332. subRecipeStepName = item["sub_recipe_step_name"].ToString();
  333. }
  334. if (!item["sub_recipe_loop_info"].Equals(DBNull.Value))
  335. {
  336. subRecipeLoopInfo = item["sub_recipe_loop_info"].ToString();
  337. }
  338. if (!item["temp_correction"].Equals(DBNull.Value))
  339. {
  340. tempCorrection = item["temp_correction"].ToString().Replace(",", ":");
  341. }
  342. if (!item["temp_pid"].Equals(DBNull.Value))
  343. {
  344. tempPid = item["temp_pid"].ToString().Replace(",", ":");
  345. }
  346. string stepNo = item["step_number"].ToString();
  347. string stepName = item["step_name"].ToString();
  348. if (DateTime.TryParse(startStepTime, out DateTime StartTime) && DateTime.TryParse(endStepTime, out DateTime EndTime))
  349. {
  350. //Annotations.Add(VerLine(Media.Brushes.AliceBlue, StartTime, Media.Brushes.Blue, $"{stepNo}"));
  351. if (EndTime < StartTime.AddSeconds(stepTime))
  352. {
  353. EndTime = StartTime.AddSeconds(stepTime);
  354. }
  355. _stepInfo.Add(new StepInfo()
  356. {
  357. StartTime = StartTime,
  358. EndTime = EndTime,
  359. StepName = stepName,
  360. StepTime = stepTime,
  361. StepNo = stepNo,
  362. StepEndTime = StartTime.AddSeconds(stepTime),
  363. SubRecipeStepNumber = subRecipeStepNumber,
  364. SubRecipeStepTime = subRecipeStepTime,
  365. SubRecipeStepName = subRecipeStepName,
  366. SubRecipeLoopInfo = subRecipeLoopInfo,
  367. TempCorrection = tempCorrection,
  368. TempPid = tempPid,
  369. });
  370. }
  371. }
  372. }
  373. }
  374. }
  375. }
  376. protected override void OnViewLoaded(object view)
  377. {
  378. base.OnViewLoaded(view);
  379. useMaxRow = (int)QueryDataClient.Instance.Service.GetConfig("System.SetUp.ExportMaxRow");
  380. this.view = (ProcessExportAllView)view;
  381. }
  382. List<string> nodeOrigin = new List<string>();
  383. void GetNode(ParameterNode pNode, bool Selected)
  384. {
  385. foreach (var item in pNode.ChildNodes)
  386. {
  387. if (item.ChildNodes.Count > 0)
  388. {
  389. GetNode(item, Selected);
  390. }
  391. else
  392. {
  393. //if(item.Selected == true)
  394. {
  395. nodeOrigin.Add(item.Name);
  396. }
  397. }
  398. }
  399. }
  400. public static int DivideAndRoundUp(int dividend, int divisor)
  401. {
  402. int result = dividend / divisor;
  403. int remainder = dividend % divisor;
  404. if (remainder > 0)
  405. {
  406. result++;
  407. }
  408. return result;
  409. }
  410. private int useMaxRow = 25000;
  411. string csv = ",";
  412. public async void ExportAll()
  413. {
  414. try
  415. {
  416. nodeOrigin.Clear();
  417. if (StepStartTime.Year == 1 || StepEndTime.Year == 1)
  418. {
  419. MessageBox.Show("No data is available in the selected period!", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  420. return;
  421. }
  422. foreach (var node in ParameterNodes)
  423. {
  424. if (node.Selected == true)
  425. {
  426. GetNode(node, node.Selected);
  427. }
  428. }
  429. if (nodeOrigin.Count == 0)
  430. {
  431. MessageBox.Show($"Please select the data you want to export.", "Export", MessageBoxButton.OK,
  432. MessageBoxImage.Warning);
  433. return;
  434. }
  435. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  436. dlg.DefaultExt = ".csv"; // Default file extension
  437. dlg.Filter = "Excel数据表格文件(*.csv)|*.csv"; // Filter files by extension
  438. dlg.FileName = $"{DisplayName}_{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}_{DateTime.Now:yyyyMMdd_HHmmss}";
  439. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  440. if (result == true) // Process open file dialog box results
  441. {
  442. BusyIndicatorContent = "Exporting start ...";
  443. IsBusy = true;
  444. Exporting?.Invoke(this, System.EventArgs.Empty);
  445. _cancellationTokenSource = new CancellationTokenSource();
  446. //System.Data.DataSet ds = new System.Data.DataSet();
  447. //var sw = new Stopwatch();
  448. //sw.Restart();
  449. //BusyIndicatorContent = "Create table header start ...";
  450. //ds.Tables.Add(new System.Data.DataTable($"{DisplayName}_{DateTime.Now:yyyyMMdd_HHmmss}"));
  451. //ds.Tables[0].Columns.Add("Recipe Info");
  452. //ds.Tables[0].Columns[0].DataType = typeof(string);
  453. //ds.Tables[0].Columns.Add("Date");
  454. //ds.Tables[0].Columns[1].DataType = typeof(string);
  455. //ds.Tables[0].Columns.Add("Time");
  456. //ds.Tables[0].Columns[2].DataType = typeof(string);
  457. //ds.Tables[0].Columns.Add("Step ID");
  458. //ds.Tables[0].Columns[3].DataType = typeof(string);
  459. //ds.Tables[0].Columns.Add("Step Name");
  460. //ds.Tables[0].Columns[4].DataType = typeof(string);
  461. StringBuilder stringBuilder = new StringBuilder();
  462. stringBuilder.AppendLine($"Recipe Info{csv}Date{csv}Time{csv}Step ID{csv}Step Name");
  463. Dictionary<T, double[]> timeValue = new Dictionary<T, double[]>();
  464. await Task.Run(() =>
  465. {
  466. for (int i = 0; i < nodeOrigin.Count; i++)
  467. {
  468. //List<Tuple<T, double>> data = (nodeOrigin[i] as ChartDataLine<T>).Points;
  469. //foreach (var tuple in data)
  470. //{
  471. // if (!timeValue.ContainsKey(tuple.Item1))
  472. // timeValue[tuple.Item1] = new double[nodeOrigin.Count];
  473. // timeValue[tuple.Item1][i] = tuple.Item2;
  474. //}
  475. // ds.Tables[0].Columns.Add(nodeOrigin[i]);
  476. // ds.Tables[0].Columns[i + 5].DataType = typeof(double);
  477. }
  478. stringBuilder.AppendLine($"Recipe:{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}");
  479. stringBuilder.AppendLine($"Start Time{csv}{string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray())}{csv}{string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray())}");
  480. stringBuilder.AppendLine($"End Time{csv}{string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray())}{csv}{string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray())}");
  481. FileHelper.Instance.SaveText(dlg.FileName, stringBuilder.ToString());
  482. //var recipeInfoRow = ds.Tables[0].NewRow();
  483. //recipeInfoRow[0] = $"Recipe:{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}";
  484. //ds.Tables[0].Rows.Add(recipeInfoRow);
  485. //recipeInfoRow = ds.Tables[0].NewRow();
  486. //recipeInfoRow[0] = $"Start Time";
  487. //recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  488. //recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  489. //ds.Tables[0].Rows.Add(recipeInfoRow);
  490. //recipeInfoRow = ds.Tables[0].NewRow();
  491. //recipeInfoRow[0] = $"End Time";
  492. //recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  493. //recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  494. //ds.Tables[0].Rows.Add(recipeInfoRow);
  495. //var rowCaption = ds.Tables[0].NewRow();
  496. //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  497. //{
  498. // rowCaption[i] = ds.Tables[0].Columns[i].Caption;
  499. //}
  500. //ds.Tables[0].Rows.Add(rowCaption);
  501. //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  502. //{
  503. // ds.Tables[0].Columns[i].Caption = null;
  504. //}
  505. DateTime startTime = startTime = StepStartTime;
  506. QueryDataClientFromTable(dlg.FileName);
  507. }, _cancellationTokenSource.Token).ContinueWith(t =>
  508. {
  509. if (t.IsCanceled || t.IsFaulted)
  510. {
  511. IsBusy = false;
  512. return;
  513. }
  514. });
  515. if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
  516. {
  517. IsBusy = false;
  518. return;
  519. }
  520. BusyIndicatorContent = "Data is written to Excel file ...";
  521. IsBusy = false;
  522. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  523. Window window = Window.GetWindow(this.view);
  524. window.Close();
  525. }
  526. }
  527. catch (Exception ex)
  528. {
  529. LOG.Write(ex);
  530. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  531. IsBusy = false;
  532. }
  533. }
  534. private void QueryDataClientFromTable(string fileName)
  535. {
  536. DateTime startTime = StepStartTime;
  537. DateTime endTime = StepEndTime;
  538. List<string> keys = new List<string>(nodeOrigin);
  539. List<string> pmList = new List<string>();
  540. List<string> systemList = new List<string>();
  541. if (keys != null && keys.Count > 0)
  542. {
  543. foreach (var dataKey in keys)
  544. {
  545. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  546. var module = dataId.Split('.').ToList()[0];
  547. if (module.ToLower() == "pm1")
  548. {
  549. pmList.Add(dataId);
  550. }
  551. else if (module.ToLower() == "system")
  552. {
  553. systemList.Add(dataId);
  554. // systemList.Add(string.Format("\"{0}\"", dataId));
  555. }
  556. }
  557. }
  558. if (StepStartTime.Date == StepEndTime.Date)
  559. {
  560. SaveDataToTable(fileName, pmList, systemList, startTime, endTime);
  561. }
  562. else
  563. {
  564. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  565. while (endTime < StepEndTime)
  566. {
  567. SaveDataToTable(fileName, pmList, systemList, startTime, endTime);
  568. startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0).AddDays(1);
  569. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  570. }
  571. SaveDataToTable(fileName, pmList, systemList, startTime, StepEndTime);
  572. }
  573. }
  574. private bool firstHeader = false;
  575. private Dictionary<string, string> GetReverseDict()
  576. {
  577. Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
  578. foreach (var kvp in _processDetailDisplayDic)
  579. {
  580. if (!keyValuePairs.ContainsKey(kvp.Value))
  581. keyValuePairs[kvp.Value] = kvp.Key.Trim().Contains(" ") ? kvp.Key.Trim().Substring(kvp.Key.Trim().LastIndexOf(" ") + 1) : kvp.Key;
  582. }
  583. return keyValuePairs;
  584. }
  585. private void SaveDataToTable(string fileName, List<string> pmList, List<string> systemList, DateTime startTime, DateTime endTime)
  586. {
  587. string stepID = "", stepName = "", subRecipeLoopInfo = "", subRecipeStepName = "", subRecipeStepNumber = "", tempCorrection = "", tempPid = "";
  588. DataTable pmDataTable = null;
  589. Dictionary<string, string> reverseDict = GetReverseDict();
  590. var columnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.PM1'";
  591. var columnTable = QueryDataClient.Instance.Service.QueryData(columnsql);
  592. List<string> col = columnTable.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  593. pmList = pmList.Where(x => col.Any(y => y == x)).ToList();
  594. string pmsql = $"select time AS InternalTimeStamp, {string.Join(",", pmList.Select(x => string.Format("\"{0}\"", x)))}";
  595. DataTable systemDataTable = null;
  596. pmsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  597. startTime.ToString("yyyyMMdd") + "." + "PM1", startTime.Ticks, endTime.Ticks);
  598. BusyIndicatorContent = "Example Query PM data ...";
  599. pmDataTable = QueryDataClient.Instance.Service.QueryData(pmsql);
  600. if (pmDataTable != null)
  601. {
  602. foreach (DataRow item in pmDataTable.Rows)
  603. {
  604. if (item.Table.Columns.Contains("PM1.APC.ModeFeedback"))
  605. {
  606. if (item.Table.Columns.Contains("PM1.APC.PressureSetPoint"))
  607. {
  608. if (item.Field<float>("PM1.APC.ModeFeedback") != 7 && item.Field<float>("PM1.APC.ModeFeedback") != 8)
  609. {
  610. item["PM1.APC.PressureSetPoint"] = 0;
  611. }
  612. }
  613. if (item.Table.Columns.Contains("PM1.APC.PositionSetPoint"))
  614. {
  615. if (item.Field<float>("PM1.APC.ModeFeedback") != 2)
  616. {
  617. item["PM1.APC.PositionSetPoint"] = 0;
  618. }
  619. }
  620. if (item.Table.Columns.Contains("PM1.APC.SlowRateSetPoint"))
  621. {
  622. if (item.Field<float>("PM1.APC.ModeFeedback") != 12)
  623. {
  624. item["PM1.APC.SlowRateSetPoint"] = 0;
  625. }
  626. }
  627. }
  628. }
  629. }
  630. var sysColumnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.System'";
  631. var sysColumnTable = QueryDataClient.Instance.Service.QueryData(sysColumnsql);
  632. List<string> systemCol = sysColumnTable.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  633. systemList = systemList.Where(x => systemCol.Any(y => y == x)).ToList();
  634. string systemsql = $"select time AS InternalTimeStamp, {string.Join(",", systemList.Select(x => string.Format("\"{0}\"", x)))}";
  635. systemsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  636. startTime.ToString("yyyyMMdd") + "." + "System", startTime.Ticks, endTime.Ticks);
  637. BusyIndicatorContent = "Example Query System data ...";
  638. systemDataTable = QueryDataClient.Instance.Service.QueryData(systemsql);
  639. int maxRow = 0;
  640. if ((pmDataTable == null || pmDataTable.Rows.Count == 0))
  641. {
  642. if (systemDataTable != null)
  643. {
  644. maxRow = systemDataTable.Rows.Count;
  645. }
  646. }
  647. else if ((systemDataTable == null || systemDataTable.Rows.Count == 0))
  648. {
  649. if (pmDataTable != null)
  650. {
  651. maxRow = pmDataTable.Rows.Count;
  652. }
  653. }
  654. else
  655. {
  656. maxRow = pmDataTable.Rows.Count > systemDataTable.Rows.Count ? systemDataTable.Rows.Count : pmDataTable.Rows.Count;
  657. }
  658. var subColNames = new List<DataColumn>() {
  659. new DataColumn("SubRecipeStepName"),
  660. new DataColumn("SubRecipeStepNumber"),
  661. new DataColumn("SubRecipeLoopInfo"),
  662. new DataColumn("TempCorrection"),
  663. new DataColumn("TempPid"),
  664. };
  665. BusyIndicatorContent = "Data is saved to excel Table ...";
  666. StringBuilder stringBuilder = new StringBuilder();
  667. if (!firstHeader)
  668. {
  669. firstHeader = true;
  670. var systemColNames = systemDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  671. {
  672. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  673. {
  674. var colAttributeName = "ColName";
  675. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  676. {
  677. colAttributeName = "DisplayName";
  678. }
  679. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  680. }
  681. return x.ColumnName;
  682. });
  683. var pmColNames = pmDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  684. {
  685. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  686. {
  687. var colAttributeName = "ColName";
  688. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  689. {
  690. colAttributeName = "DisplayName";
  691. }
  692. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  693. }
  694. return x.ColumnName;
  695. });
  696. stringBuilder.AppendLine($"{csv}{csv}{csv}{csv}{csv}{string.Join($"{csv}", subColNames.Cast<DataColumn>())} {csv}{string.Join($"{csv}", systemColNames ?? new string[0])} {csv}{string.Join($"{csv}", pmColNames ?? new string[0])}");
  697. }
  698. for (int i = 0; i < maxRow; i++)
  699. {
  700. BusyIndicatorContent = $"Total data {maxRow} current {i + 1} ...";
  701. var pmRow = pmDataTable != null && pmDataTable.Rows.Count > 0 ? pmDataTable.Rows[i] : null;
  702. var systemRow = systemDataTable != null && systemDataTable.Rows.Count > 0 ? systemDataTable.Rows[i] : null;
  703. //float timeIndex = 0;
  704. //float.TryParse(item.Key.ToString(), out timeIndex);
  705. //DateTime dateTimeKey = startTime.AddMilliseconds(timeIndex * 1000); ;// DateTime.Parse(item.Key.ToString());
  706. DateTime dateTimeKey = new DateTime(systemRow != null ? (long)systemRow[0] : (long)pmRow[0]);
  707. var tempStepInfo = _stepInfo.OrderByDescending(x => x.StartTime).Where(x => x.StartTime <= dateTimeKey).FirstOrDefault();
  708. if (tempStepInfo != null)// && dateTimeKey > _stepInfo[iIndex].StartTime && x.StepEndTime >= dateTimeKey
  709. {
  710. stepID = tempStepInfo.StepNo;
  711. stepName = tempStepInfo.StepName;
  712. subRecipeStepName = tempStepInfo.SubRecipeStepName;
  713. subRecipeStepNumber = tempStepInfo.SubRecipeStepNumber;
  714. subRecipeLoopInfo = !string.IsNullOrEmpty(tempStepInfo.SubRecipeLoopInfo) ? tempStepInfo.SubRecipeLoopInfo.Replace("/", "|") : tempStepInfo.SubRecipeLoopInfo;
  715. tempCorrection = !string.IsNullOrEmpty(tempStepInfo.TempCorrection) ? tempStepInfo.TempCorrection : "";
  716. tempPid = !string.IsNullOrEmpty(tempStepInfo.TempPid) ? tempStepInfo.TempPid : "";
  717. }
  718. if (pmRow == null && systemRow != null)
  719. {
  720. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", systemRow.ItemArray.ToList().GetRange(1, systemRow.ItemArray.Count() - 1).Select(x => x.ToString()))}{csv}{string.Join($"{csv}", Enumerable.Repeat("", pmDataTable?.Columns.Count ?? 0).ToArray())}");
  721. }
  722. else if (pmRow != null && systemRow == null)
  723. {
  724. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", Enumerable.Repeat("", systemDataTable?.Columns?.Count ?? 0).ToArray())}{csv}{string.Join($"{csv}", pmRow.ItemArray.ToList().GetRange(1, pmRow.ItemArray.Count() - 1).Select(x => x.ToString()))}");
  725. }
  726. else if (systemDataTable != null)
  727. {
  728. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", systemDataTable.Rows[i].ItemArray.ToList().GetRange(1, systemDataTable.Rows[i].ItemArray.Count() - 1).Select(x => x.ToString()))}{csv}{string.Join($"{csv}", pmDataTable.Rows[i].ItemArray.ToList().GetRange(1, pmDataTable.Rows[i].ItemArray.Count() - 1).Select(x => x.ToString()))}");
  729. }
  730. if (i == maxRow - 1)
  731. {
  732. var str = stringBuilder.ToString();
  733. str = str.TrimEnd((new char[] { '\r', '\n' }));
  734. FileHelper.Instance.SaveNewLineDataToTxt(fileName, str, true);
  735. stringBuilder.Clear();
  736. }
  737. }
  738. }
  739. static string CheckAndReplace(string input)
  740. {
  741. if (input.StartsWith("PM1"))
  742. {
  743. return input.Substring(4);
  744. }
  745. if (input.StartsWith("System"))
  746. {
  747. return input.Substring(7);
  748. }
  749. return input;
  750. }
  751. /// <summary>
  752. /// 取消查询。
  753. /// </summary>
  754. public void CancelQuery()
  755. {
  756. Task.Run(() =>
  757. {
  758. if (_cancellationTokenSource?.Token.CanBeCanceled == true)
  759. {
  760. _cancellationTokenSource.Cancel();
  761. }
  762. Thread.Sleep(100);
  763. //_progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  764. //_progChartSuspendUpdating.Report(false);
  765. });
  766. }
  767. }
  768. }